-#! /usr/bin/env python
+#! /usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
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()
else:
getNSparams()
# keep print, stdout used in shell
- print my_host, my_port
+ print(my_host, my_port)
pass
pass
#
-#!/usr/bin/env python
+#!/usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
# 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)
-#!/usr/bin/env python
+#!/usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2017 CEA/DEN, EDF R&D, OPEN CASCADE
#
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
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)
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)
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))
# write config
logger.debug("write config: %s"%str(config))
try:
- with open(config_file, 'w') as f:
+ with open(config_file, 'wb') as f:
pickle.dump(config, f)
except IOError:
pass
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)
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
# write config
logger.debug("write config: %s"%str(config))
try:
- with open(config_file, 'w') as f:
+ with open(config_file, 'wb') as f:
pickle.dump(config, f)
except IOError:
pass
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)
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
-#! /usr/bin/env python
+#! /usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
"""
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):
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=[]
# 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
# 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
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
pass
if __name__ == "__main__":
- if verbose(): print sys.argv
+ if verbose(): print(sys.argv)
addToKillList(sys.argv[1], sys.argv[2])
pass
-#! /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,
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"] = []
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:
- print "Configure parser: Error : can not read configuration file %s, check existence and rights" % filename
+ 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
+ for cle,val in list(_config.items()):
+ print(cle, val)
pass
# Remove CTestTestfile.cmake; this file will be filled by successive calls to link_module and link_extra_test
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
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
# 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
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)
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)
#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)
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)
"""
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
applipath = relpath(os.path.realpath(os.path.dirname(__file__)),os.path.realpath(os.getenv('HOME')))
else:
applipath = get_appli_path()
- print applipath
+ print(applipath)
#
"""
"""
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.
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
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()
-#! /usr/bin/env python
+#! /usr/bin/env python3
# Copyright (C) 2013-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
configFileNames, args, unexisting = getConfigFileNames(args, checkExistence=True)
if len(unexisting) > 0:
- print "ERROR: unexisting configuration/environment file(s): " + ', '.join(unexisting)
+ print("ERROR: unexisting configuration/environment file(s): " + ', '.join(unexisting))
sys.exit(1)
# Create a SalomeContext which parses configFileNames to initialize environment
sys.stdout.write(out)
if err:
sys.stderr.write(err)
- #print 'Thank you for using SALOME!'
+ # print('Thank you for using SALOME!')
sys.exit(returncode)
- except SalomeContextException, e:
+ except SalomeContextException as e:
import logging
logging.getLogger("salome").error(e)
sys.exit(1)
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)
try:
from salomeContextUtils import setOmniOrbUserPath
setOmniOrbUserPath()
- except Exception, e:
- print e
+ except Exception as e:
+ print(e)
sys.exit(1)
# End of preliminary work
#
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()
#
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."""
# 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":
setOmniOrbUserPath()
# Set timeout handler
- print "Test timeout explicitely set to: %s seconds"%timeout_delay
+ print("Test timeout explicitely set to: %s seconds"%timeout_delay)
timeout_sec = abs(int(timeout_delay)-10)
if sys.platform == 'win32':
from threading import Timer
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()
pass
if sys.platform == 'win32':
timer.cancel()
- print "Exit test with status code:", res
+ print("Exit test with status code:", res)
sys.exit(res)
#
# 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
setOmniOrbUserPath()
# Set timeout handler
- print "Test timeout explicitely set to: %s seconds"%timeout_delay
+ print("Test timeout explicitely set to: %s seconds"%timeout_delay)
timeout_sec = abs(int(timeout_delay)-10)
if sys.platform == 'win32':
from threading import Timer
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()
pass
if sys.platform == 'win32':
timer.cancel()
-# print "Exit test with status code:", res
+# print("Exit test with status code:", res)
# sys.exit(res)
#
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)
#
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()
#
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
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"],))
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()
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()
port = getPort(prefered)
else:
port = getPort()
- print "obtained port = %s"%port
+ print("obtained port = %s"%port)
obtained_ports.put(port)
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 = [
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()
p.join()
# Release port
- print "release port 2899"
+ print ("release port 2899")
p = multiprocessing.Process(target=releasePort, args=(2899,))
p.start()
p.join()
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,))
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")
#
#
-print 'Hello!'
+print('Hello!')
# make hello.py
echo "
#!/usr/bin/env python
-print 'Hello\!'
+print('Hello\!')
" > ${BASE_DIR}/hello.py
# Build output folders
import os
import sys
import imp
-from cStringIO import StringIO
+from io import StringIO
import logging
logger = logging.getLogger("TestLauncherLogger")
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
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()
#
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)
#
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)
#
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()
#
# 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()
#
"""
"""
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
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
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")
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
mach.update()
#dump new CatalogResources.xml
- f=open(catalog_file,'w')
- f.write('<?xml version="1.0" ?>\n')
- doc.write(f)
- f.write('\n')
- f.close()
- print "%s updated" % catalog_file
+ with open(catalog_file,'w') as f:
+ f.write('<?xml version="1.0" ?>\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=[]
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__':
-#! /usr/bin/env python
+#! /usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
-#! /usr/bin/env python
+#! /usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
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)
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)
try:
from salomeContextUtils import setOmniOrbUserPath
setOmniOrbUserPath()
- except Exception, e:
- print e
+ except Exception as e:
+ print(e)
sys.exit(1)
killAllPorts()
pass
-#! /usr/bin/env python
+#! /usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2017 CEA/DEN, EDF R&D, OPEN CASCADE
#
# \endcode
#
-import os, sys, pickle, signal, commands,glob
+import os, sys, pickle, signal, subprocess,glob
import subprocess
import shlex
from salome_utils import verbose
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")
# 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)
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
log_msg += " ... not found\n"
if verbose():
- print log_msg
+ print(log_msg)
return filedict
#
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
if __name__ == "__main__":
if len(sys.argv) < 2:
- print "Usage: "
- print " %s <port>" % os.path.basename(sys.argv[0])
- print
- print "Kills SALOME session running on specified <port>."
+ print("Usage: ")
+ print(" %s <port>" % os.path.basename(sys.argv[0]))
+ print()
+ print("Kills SALOME session running on specified <port>.")
sys.exit(1)
pass
if sys.argv[1] == "--spy":
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)
# 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"
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:
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:
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
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)
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
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 # <module> section
else:
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
# 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 (inly 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 <log-file>"
- o_f = optparse.Option("-f",
- "--log-file",
- metavar="<log-file>",
- type="string",
- action="store",
- dest="log_file",
- help=help_str)
+ pars.add_argument("-f",
+ "--log-file",
+ metavar="<log-file>",
+ dest="log_file",
+ help=help_str)
# Configuration XML file. Default: see defaultUserFile() function
- help_str = "Parse application settings from the <file> "
+ help_str = "Parse application settings from the <file> "
help_str += "instead of default %s" % defaultUserFile()
- o_r = optparse.Option("-r",
- "--resources",
- metavar="<file>",
- type="string",
- action="store",
- dest="resources",
- help=help_str)
+ pars.add_argument("-r",
+ "--resources",
+ metavar="<file>",
+ 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 <module1>, <module2> are the names "
help_str += "of SALOME modules which should be available in the SALOME session)"
- o_m = optparse.Option("-m",
- "--modules",
- metavar="<module1,module2,...>",
- type="string",
- action="append",
- dest="modules",
- help=help_str)
+ pars.add_argument("-m",
+ "--modules",
+ metavar="<module1,module2,...>",
+ 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 <serverN>: %s " % ", ".join( embedded_choices )
help_str += "[by default the value from the configuration files is used]"
- o_e = optparse.Option("-e",
- "--embedded",
- metavar="<server1,server2,...>",
- type="string",
- action="callback",
- dest="embedded",
- callback=check_embedded,
- help=help_str)
+ pars.add_argument("-e",
+ "--embedded",
+ metavar="<server1,server2,...>",
+ 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 <serverN>: %s " % ", ".join( standalone_choices )
help_str += "[by default the value from the configuration files is used]"
- o_s = optparse.Option("-s",
- "--standalone",
- metavar="<server1,server2,...>",
- type="string",
- action="callback",
- dest="standalone",
- callback=check_standalone,
- help=help_str)
+ pars.add_argument("-s",
+ "--standalone",
+ metavar="<server1,server2,...>",
+ 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="<N>",
- type="int",
- action="store",
- dest="interp",
- help=help_str)
+ pars.add_argument("-i",
+ "--interp",
+ metavar="<N>",
+ 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="<ns_port_log_file>",
- type="string",
- action="store",
- dest="ns_port_log_file",
- help=help_str)
+ pars.add_argument("--ns-port-log",
+ metavar="<ns_port_log_file>",
+ 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="<test_script_file>",
- type="string",
- action="store",
- dest="test_script_file",
- help=help_str)
+ pars.add_argument("--test",
+ metavar="<test_script_file>",
+ 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="<play_script_file>",
- type="string",
- action="store",
- dest="play_script_file",
- help=help_str)
+ pars.add_argument("--play",
+ metavar="<play_script_file>",
+ 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 setted, 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",
+ 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="<server_launch_mode>",
- type="choice",
- choices=["daemon","fork"],
- action="store",
- dest="server_launch_mode",
- help=help_str)
+ pars.add_argument("--server-launch-mode",
+ metavar="<server_launch_mode>",
+ 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="<port>",
- type="int",
- action="store",
- dest="use_port",
- help=help_str)
+ pars.add_argument("--port",
+ metavar="<port>",
+ 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
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 "<appname>Config" (SalomeAppConfig) which can
# 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 <moduleN>_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
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
_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
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
# 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:
# 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 ),
if cmd_opts.wake_up_session is not None:
args[wake_up_session_nam] = cmd_opts.wake_up_session
- ####################################################
- # Add <theAdditionalOptions> 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"
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
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
-#!/usr/bin/env python
+#!/usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
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]
try:
os.mkdir(upath)
except:
- #print "Can't create " + upath
+ # print("Can't create " + upath)
pass
#os.system("touch " + upath + "/dummy")
#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:
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):
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
if test:
NamingServer(args).run()
pass
- print "Searching Naming Service ",
+ print("Searching Naming Service ", end=' ')
ncount=0
delta=0.1
while(ncount < 100):
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)
# --------------------------------------------------------------------------
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 = []
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
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('+')
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":
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('+')
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
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
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('+')
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
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-import ConfigParser
+import configparser
import os
import logging
import re
#
# :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
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()
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)
# 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:
# 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)
#
# 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)
#
from optparse import OptionParser
import os
import sys
-import user
import pickle
# Use to display newlines (\n) in epilog
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)
)
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)
#
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
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
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"):
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()
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!")
#
echo ""
echo " to run IDLparser:"
echo ""
- echo " $0 -Wbcatalog=<my_catalog.xml>[,icon=<pngfile>][,version=<num>][,author=<name>][,name=<component_name>][,multistudy=<component_multistudy>][,remove=component_name] <file.idl> "
+ echo " $0 -Wbcatalog=<my_catalog.xml>[,icon=<pngfile>][,version=<num>][,author=<name>][,name=<component_name>][,remove=component_name] <file.idl> "
echo ""
echo " to have omniidl help:"
echo ""
-#!/usr/bin/env python
+#!/usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
try:
killMyPort(my_port)
except:
- print "problem in killLocalPort()"
+ print("problem in killLocalPort()")
pass
pass
try:
killMyPort(my_port)
except:
- print "problem in LocalPortKill(), killMyPort(%s)"%port
+ print("problem in LocalPortKill(), killMyPort(%s)"%port)
pass
pass
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
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)
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
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
# ---
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
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']
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
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:
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
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"]:
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
#
"""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'])
#
# 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
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']:
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()
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
runSalome, with --killall option, starts with killing
the processes resulting from the previous execution.
- """%filedict
+ """%filedict)
#
# Print Naming Service directory list
if clt != None:
if verbose():
- print
- print " --- registered objects tree in Naming Service ---"
+ print()
+ print(" --- registered objects tree in Naming Service ---")
clt.showNS()
pass
# 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)
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]
# -----------------------------------------------------------------------------
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
#
def runSalome():
- import user
clt,args = main()
# --
test = args['gui'] and args['session_gui']
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
# 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)
# 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
# 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
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
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)
return []
if args[0] in ["-h", "--help"]:
- print usage + epilog
+ print(usage + epilog)
sys.exit(0)
return args
import os
import sys
import logging
-import ConfigParser
+import configparser
from parseConfigFile import parseConfigFile
any blank characters.
'''
- print msg
+ print(msg)
#
"""
#
def __loadMPI(self, module_name):
- print "Trying to load MPI module: %s..."%module_name,
+ print("Trying to load MPI module: %s..."%module_name)
try:
out, err = subprocess.Popen(["modulecmd", "python", "load", module_name], stdout=subprocess.PIPE).communicate()
- exec out # define specific environment variables
- print " OK"
+ exec(out) # define specific environment variables
+ print(" OK")
except:
- print " ** Failed **"
+ print(" ** Failed **")
pass
#
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(['python', 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
#
'car' : '_getCar',
}
- if not command in availableCommands.keys():
+ if command not in availableCommands:
command = "start"
options = args
try:
res = getattr(self, command)(options) # run appropriate method
return res or 0
- except SystemExit, returncode:
+ except SystemExit as returncode:
if returncode != 0:
self.getLogger().error("SystemExit %s in method %s.", returncode, command)
return returncode
- except StandardError:
+ except Exception:
self.getLogger().error("Unexpected error:")
import traceback
traceback.print_exc()
return 1
- except SalomeContextException, e:
+ except SalomeContextException as e:
self.getLogger().error(e)
return 1
#
reserved = []
try:
unsetVars, configVars, reservedDict = parseConfigFile(filename, reserved)
- except SalomeContextException, e:
+ except SalomeContextException as e:
msg = "%s"%e
self.getLogger().error(msg)
return 1
# 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"]:
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)
args = []
ports = args
if not ports:
- print "Port number(s) not provided to command: salome kill <port(s)>"
+ print("Port number(s) not provided to command: salome kill <port(s)>")
return 1
from multiprocessing import Process
#
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 = {}
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):
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:
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:
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
modules = args
if not modules:
- print "Module(s) not provided to command: salome doc <module(s)>"
+ print("Module(s) not provided to command: salome doc <module(s)>")
return 1
appliPath = os.getenv("ABSOLUTE_APPLI_PATH")
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
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)
-#! /usr/bin/env python
+#! /usr/bin/env python3
# Copyright (C) 2013-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
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:
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")
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))
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
fn.close()
except:
pass
- if not ispython and currentScript[-3:] == ".py":
+ if not ispython and script_extension == ".py":
currentKey = "@PYTHONBIN@ "+currentScript
else:
currentKey = currentScript
are supported.
If <arg> 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
### 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
# ---
-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.
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
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)
ret = 1
pass
pass
- except OSError, e:
+ except OSError as e:
# errno.ESRCH == 3 is 'No such process'
if e.errno == 3:
ret = 0
-#!/usr/bin/env python
+#!/usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
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'],
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:
-#!/usr/bin/env python
+#!/usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
+ 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
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)
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)
-#!/usr/bin/env python
+#!/usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
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):
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)]
# 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 <module>_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"] :
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
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]
"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
# 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]
-#!/usr/bin/env python
+#!/usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
-# -*- 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,
#
# 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.
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
"""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
"""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
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
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
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')
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 <appli_path>/bin/salome/test/<module> to <module_path>/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
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):
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
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")
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
#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
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
#directory bin/salome/test : create it and link content
if os.path.exists(extra_test_dir):
# link <appli_path>/bin/salome/test/<extra_test> to <extra_test_path>/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
# -----------------------------------------------------------------------------
-#!/usr/bin/env python
+#!/usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
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)
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()
-#!/usr/bin/env python
+#!/usr/bin/env python3
# -*- coding: iso-8859-1 -*-
# Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
#
#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!"
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!"
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!"
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
#============================================================
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!"
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")
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
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!"
#============================================================
res, A = father.FindAttribute("AttributeTextHighlightColor")
-print res, A
+print(res, A)
if res == 0 or A == None:
raise RuntimeError, "Error: not found AttributeTextHighlightColor"
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")
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
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!"
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")
A.SetValue(763242882)
if A.Value() != 763242882:
- print "Error: wrong value of AttributeLocalID"
+ print("Error: wrong value of AttributeLocalID")
# save / restore study
#=================================
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!"
A = A._narrow(SALOMEDS.AttributeLocalID)
if A.Value() != 763242882:
- print "Error: wrong value of AttributeLocalID"
+ print("Error: wrong value of AttributeLocalID")
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 ------------------------------------------
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()
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()
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 ---------------------------------
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!"
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!"
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!"
A.SetValue("AttributesTesting")
if A.Value() != "AttributesTesting":
- print "Wrong value of AttributeName"
+ print("Wrong value of AttributeName")
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=[]
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"
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())
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
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
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
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
# ---- 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");
# ---- 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,
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,
# ---- 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 );
# ---- 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)
#=======================================================
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()
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 immediatly
-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
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 "Befor save ",
+print("Befor 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)
#=================================
#==================================================
#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!"
#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)
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, "defferent length of nodes after study open"
#aChildIterator.Next()
#==================================================
#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!"
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, "defferent length of nodes after study open"
#aChildIterator.Next()
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
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)
#--------------------------------------------------------------------------#
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!"
#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)
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
#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"]
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 -----------------------------------#
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!"
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())
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
#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"]
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 -----------------------------------#
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!"
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())
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")
-
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
#=================================
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!"
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))
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
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!"
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")
A.SetValue("AttributesTesting")
if A.Value() != "AttributesTesting":
- print "Wrong value of AttributeName"
+ print("Wrong value of AttributeName")
# save / restore study
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!"
raise RuntimeError, "Can't create AttributeName attribute"
if A.Value() != "AttributesTesting":
- print "Wrong value of AttributeName"
+ print("Wrong value of AttributeName")
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!"
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!"
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!"
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!"
\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
# 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")
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
(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.
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
extStudy_1.object
extStudy_2.object
extStudy_3.object
-myStudyManager.object
SalomeAppEngine.object
\endcode
# 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)
\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
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)] != '__' \
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)
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")
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,"*")
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
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
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:
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))
{
/*! \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
*/
*/
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<string> ListOfOpenStudies;
//! List of file names
typedef sequence<string> ListOfFileNames;
//! List of modification dates of a study
interface GenericAttribute;
interface Study;
- interface StudyManager;
interface StudyBuilder;
interface SObject;
interface SComponent;
//! 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
- <BR><VAR>The Path </VAR>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 '/'.
- <BR><VAR>The Context</VAR> is the current directory of an object.</P>
+ 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
+ <BR><VAR>The Tag</VAR> 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: <TT>0:2:1:1</TT>
*/
+ //==========================================================================
- 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<SObject> 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
+<em>See \ref example17 for an example of this method usage in batchmode of %SALOME application.</em>
- \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);
-<em>See \ref example1 for an example of this method usage in batchmode of %SALOME application.</em>
+/*! \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
-<em>See \ref example19 for an example of this method usage in batchmode of %SALOME application.</em>
-*/
- 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.
+<em>See \ref example18 for an example of this method usage in batchmode of %SALOME application.</em>
- \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 <VAR>anObjectName</VAR>.
- \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
-<em>See \ref example23 for an example of this method usage in batchmode of %SALOME application.</em>
*/
- 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
-<em>See \ref example23 for an example of this method usage in batchmode of %SALOME application.</em>
-*/
- 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 <VAR>theContext</VAR> 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 <VAR>theContext</VAR> 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 <VAR>theContext</VAR> 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 <VAR>theContext</VAR> 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);
+<em>See \ref example19 for an example of this method usage in batchmode of %SALOME application.</em>
-/*! \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.
-<em>See \ref example20 for an example of this method usage in batchmode of %SALOME application.</em>
+<em>See \ref example1 for an example of this method usage in batchmode of %SALOME application.</em>
*/
- 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.
+ */
-<em>See \ref example20 for an example of this method usage in batchmode of %SALOME application.</em>
+ 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.
+<em>See \ref example17 for an example of this method usage in batchmode of %SALOME application.</em>
*/
- 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);
+<em>See \ref example3 for an example of this method usage in batchmode of %SALOME application.</em>
-/*! \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);
+<em>See \ref example16 for an example of this method usage in batchmode of %SALOME application.</em>
- 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 Cancelation 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.
+<em>See \ref example17 for an example of this method usage in batchmode of %SALOME application.</em>
*/
- 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
+<em>See \ref example16 for an example of this method usage in batchmode of %SALOME application.</em>
- (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);
+<em>See \ref example16 for an example of this method usage in batchmode of %SALOME application.</em>
-/*! \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
+<em>See \ref example16 for an example of this method usage in batchmode of %SALOME application.</em>
- \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
+<em>See \ref example3 for an example of this method usage in batchmode of %SALOME application.</em>
- \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
+ <BR><VAR>The Path </VAR>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 '/'.
+ <BR><VAR>The Context</VAR> is the current directory of an object.</P>
*/
- 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<SObject> 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.
+<em>See \ref example1 for an example of this method usage in batchmode of %SALOME application.</em>
- \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.
+<em>See \ref example19 for an example of this method usage in batchmode of %SALOME application.</em>
*/
- 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
- <BR><VAR>The Tag</VAR> 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: <TT>0:2:1:1</TT>
+ \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 <VAR>anObjectName</VAR>.
+ \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.
-
-<em>See \ref example17 for an example of this method usage in batchmode of %SALOME application.</em>
+ 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.
-<em>See \ref example18 for an example of this method usage in batchmode of %SALOME application.</em>
+ \return A new %StudyBuilder.
+<em>See \ref example20 for an example of this method usage in batchmode of %SALOME application.</em>
*/
+ 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
+<em>See \ref example20 for an example of this method usage in batchmode of %SALOME application.</em>
*/
- 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.
-
-<em>See \ref example19 for an example of this method usage in batchmode of %SALOME application.</em>
+ 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
-<em>See \ref example1 for an example of this method usage in batchmode of %SALOME application.</em>
+ 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);
-<em>See \ref example17 for an example of this method usage in batchmode of %SALOME application.</em>
+/*! \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.
-
-<em>See \ref example23 for an example of this method usage in batchmode of %SALOME application.</em>
-
+ 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"
+<em>See \ref example1 for an example of this method usage in batchmode of %SALOME application.</em>
*/
-
- 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.
-
-<em>See \ref example3 for an example of this method usage in batchmode of %SALOME application.</em>
-
+ 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.
-
-<em>See \ref example16 for an example of this method usage in batchmode of %SALOME application.</em>
-
+ 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 Cancelation of the command
-
- Cancels all actions declared within the command.
+ SObject Paste(in SObject theObject) raises (SALOMEDS::StudyBuilder::LockProtection);
-<em>See \ref example17 for an example of this method usage in batchmode of %SALOME application.</em>
+/*! \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);
-<em>See \ref example16 for an example of this method usage in batchmode of %SALOME application.</em>
+ 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);
-<em>See \ref example16 for an example of this method usage in batchmode of %SALOME application.</em>
+/*! \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);
-<em>See \ref example16 for an example of this method usage in batchmode of %SALOME application.</em>
+/*! \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);
-<em>See \ref example3 for an example of this method usage in batchmode of %SALOME application.</em>
-*/
- 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);
-<em>See \ref example17 for an example of this method usage in batchmode of %SALOME application.</em>
+/*! \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
-<em>See \ref example1 for an example of this method usage in batchmode of %SALOME application.</em>
+ \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);
-<em>See \ref example19 for an example of this method usage in batchmode of %SALOME application.</em>
-*/
- 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 whcih 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
-<em>See \ref example1 for an example of this method usage in batchmode of %SALOME application.</em>
+ 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 whcih 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
*/
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.
can be called by any component and which provide the following functionality:
<ul>
<li> publishing in the study of the objects created by a definite component
- <li> 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.
+ <li> 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.
<li> transforming of the transient references into persistant references (or vice versa) of the SObjects when saving (or loading) a study
<li> copy/paste common functionality. These methods can be called by any component in order to copy/paste its object created in the study
</ul>
/*! \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.
/*! \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.
/*! \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
/*! \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
/*! \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
*/
/*! \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
\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
\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.
/*!
Warning: no internal registration is done, so it is up to the caller to
manage the various instanciation.
\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.
*/
\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.
/*!
//! 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.
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);
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
/*!
ComponentType type;
string name;
string username;
- boolean multistudy;
ImplType implementationType;
string implname;
string icon;
*/
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 ;
// 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();
};
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 ;
} ;
{
//! 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();
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() ;
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);
<component-author>NRI</component-author>
<component-version>@SALOMEKERNEL_VERSION@</component-version>
<component-comment>GUI Neutral Context</component-comment>
- <component-multistudy>1</component-multistudy>
<constraint>hostname = muna</constraint>
</component>
<component-author>NRI</component-author>
<component-version>@SALOMEKERNEL_VERSION@</component-version>
<component-comment>GUI Neutral Context</component-comment>
- <component-multistudy>1</component-multistudy>
<constraint>'linux' ~ OS</constraint>
</component>
<component>
<component-author>NRI</component-author>
<component-version>@SALOMEKERNEL_VERSION@</component-version>
<component-comment>GUI Neutral Context</component-comment>
- <component-multistudy>1</component-multistudy>
<constraint>'linux' ~ OS</constraint>
</component>
</component-list>
-#!/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
# Current the script does:
# 1. remove Python documentation in triple double quotes (like """some_comments""")
#
-# Usage: prepare_generating_doc.py [-o <output_file>] <input_file>
+# Usage: prepare_generating_doc.py [-o <output_file>] <input_file>
#
# If <output_file> 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')
pass
if not output_file: output_file = os.path.basename(input_file)
-
+
# open output file
try:
outfile = open(output_file, 'wb')
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:
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
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"
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
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
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
AC_SUBST(PYTHONHOME)
changequote(<<, >>)dnl
- PYTHON_VERSION=`$PYTHON -c "import sys; print sys.version[:3]"`
+ PYTHON_VERSION=`$PYTHON -c "import sys; print(sys.version[:3])"`
changequote([, ])dnl
AC_SUBST(PYTHON_VERSION)
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,
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="</Path/to/the/sources/of/application>",
- 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="<module1,module2,...>",
- 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",
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)
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
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) )
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" )
#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 )
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" ]
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 :
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 )
-print "Hello world"
+print("Hello world")
# 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 )
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
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 );
// /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 );
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()
{
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
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}
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
_Executed(false) ,
_graphName("") ,
_nodeName(""),
- _studyId(-1),
_id(0),
_contId(0),
_CanceledThread(false)
_Executed(false) ,
_graphName("") ,
_nodeName(""),
- _studyId(-1),
_id(0),
_contId(0),
_CanceledThread(false)
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
return dynamic_cast<Engines_Container_i*>(_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
*/
//=============================================================================
-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;
if(_NS)
delete _NS;
for(std::map<std::string,Engines::PyNode_var>::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<std::string,Engines::PyScriptNode_var>::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();
+ }
}
//=============================================================================
*/
std::map<std::string, Engines::EngineComponent_var>::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());
//=================================================================
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;
//=================================================================
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;
//=================================================================
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;
// (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
//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;
_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();
(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;
}
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;
}
* 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;
}
* 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
//=============================================================================
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;
//! 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
*/
//=============================================================================
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)
{
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());
//! 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() ;
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);
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();
}
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);
* 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
*
Engines::EngineComponent_ptr
Engines_Container_i::createInstance(std::string genericRegisterName,
void *handle,
- int studyId,
std::string& reason)
{
// --- find the factory
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<Engines_Component_i*>(_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)
* 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<std::string,Engines::EngineComponent_var>::iterator itm =_listInstances_map.begin();
if (instance.find(registeredName) == 0)
{
anEngine = (*itm).second;
- if (studyId == anEngine->getStudyId())
- {
- return anEngine._retn();
- }
+ return anEngine._retn();
}
itm++;
}
{
iobject = createInstance(genericRegisterName,
handle,
- 0,
- reason); // force multiStudy instance here !
+ reason);
}
else
{
iobject = Engines::EngineComponent::_narrow( obj ) ;
- Engines_Component_i *servant =
- dynamic_cast<Engines_Component_i*>
- (_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 (...)
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");
+ }
}
//=============================================================================
//=============================================================================
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<std::string,Engines::PyNode_var>::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<std::string,Engines::PyNode_var>::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);
+ }
}
//=============================================================================
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();
+ }
}
//=============================================================================
//=============================================================================
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<std::string,Engines::PyScriptNode_var>::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<std::string,Engines::PyScriptNode_var>::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);
+ }
}
//=============================================================================
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();
+ }
}
//=============================================================================
}
_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;
+}
+*/
// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
//
-#include <time.h>
+#include <Python.h>
+#include <structmember.h>
#ifndef WIN32
#include <sys/time.h>
#endif
#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())
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
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;
}
-
#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);
from SALOME_utilities import *
-from thread import *
+from _thread import *
#=============================================================================
_orb = None
_poa = None
_fieldsDict = []
- _studyId = -1
#-------------------------------------------------------------------------
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
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) ")
#-------------------------------------------------------------------------
#-------------------------------------------------------------------------
- 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 ""
#-------------------------------------------------------------------------
void ping();
void destroy();
- CORBA::Long getStudyId();
Engines::Container_ptr GetContainerRef();
void setProperties(const Engines::FieldsDict& dico);
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);
// 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();
std::string getContainerName();
void setContainerName();
- virtual bool setStudyId(CORBA::Long studyId);
- static bool isMultiStudy();
static bool isMultiInstance();
static std::string GetDynLibraryName(const char *componentName);
Salome_file_i * file);
protected:
- int _studyId; // -1: not initialised; 0: multiStudy; >0: study
- static bool _isMultiStudy;
static bool _isMultiInstance;
std::string _instanceName ;
import os
import sys
-import string
import traceback
import imp
from omniORB import CORBA, PortableServer
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)
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:
#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=""
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
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)
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
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
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)
#-------------------------------------------------------------------------
# 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()
#Block for ever
orb.run()
- if verbose():print "SALOME_ContainerPy_i shutdown"
+ if verbose():print("SALOME_ContainerPy_i shutdown")
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);
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,
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);
# Module : SALOME
# $Header$
#
-import sys,traceback,string
+import sys,traceback
import linecache
-import cPickle
+import pickle
import Engines__POA
import SALOME__POA
import SALOME
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):
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()
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))
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()
{
_id = -1;
_type = theDocumentType;
- _modified = true;
+ _modified = false;
}
DF_Document::~DF_Document()
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})
%init
%{
+#include <capsulethunk.h>
// init section
-
#ifdef WITH_NUMPY
import_array()
#endif
{
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");
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";
}
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 acces 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 acces option");
- }
}
void HDFfile::CloseOnDisk()
def __init__(self, aDoc):
self.doc = aDoc
def __repr__(self):
- print self.doc
+ print(self.doc)
return "---"
def salome(self):
doc_salome = '''
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
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 = '''
--- 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 = '''
and GraphExample.xml
---
'''
- print doc_supervision
+ print(doc_supervision)
#--------------------------------------------------------------------------
-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()
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]
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)
#--------------------------------------------------------------------------
#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)
- 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
- 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
# \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)
#
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)
# 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 intialisation 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 !
+ Performs only once SALOME general purpose initialization for scripts.
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 intented 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
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
#--------------------------------------------------------------------------
#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
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
-def PersistentPresentation(theStudy, theSO, theWithID):
+def PersistentPresentation(theSO, theWithID):
# put the sobject's content (with subchildren) to the string
aResult = ""
attrs = theSO.GetAllAttributes()
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
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, "<CanCopy> for "+theInfo+" returns false"
+ if not myStudy.CanCopy(theSO):
+ raise RuntimeError("<CanCopy> for "+theInfo+" returns false")
- if not myStudyManager.Copy(theSO):
- raise RuntimeError, "<Copy> for "+theInfo+" returns false"
+ if not myStudy.Copy(theSO):
+ raise RuntimeError("<Copy> for "+theInfo+" returns false")
- if not myStudyManager.CanPaste(theSO):
- raise RuntimeError, "<CanPaste> for "+theInfo+" returns false"
+ if not myStudy.CanPaste(theSO):
+ raise RuntimeError("<CanPaste> for "+theInfo+" returns false")
# check: before paste study is not changed check
- if aStudyPersist != PersistentPresentation(myStudy, aRoot, 1):
- raise RuntimeError, "Study is changed before Paste calling for "+theInfo
+ if aStudyPersist != PersistentPresentation(aRoot, 1):
+ raise RuntimeError("Study is changed before Paste calling for "+theInfo)
aSObj = theSO
if theComponentPaste:
aSObj = theSO.GetFatherComponent()
theInfo = theInfo + "(paste for component)"
- if myStudyManager.Paste(aSObj) == None:
- raise RuntimeError, "<Paste> for "+theInfo+" returns None object"
+ if myStudy.Paste(aSObj) == None:
+ raise RuntimeError("<Paste> for "+theInfo+" returns None object")
aNewTree = GetTree(aRoot)
aLen = len(aTree)
for a in range(0,aLen):
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):
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)
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()
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"""
#
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
return True
if __name__ == "__main__":
- import unittester
+ from . import unittester
unittester.run("salome/kernel/__init__","TEST_serialization")
__author__="gboulant"
__date__ ="$15 avr. 2010 19:44:17$"
-from uiexception import DevelException
+from .uiexception import DevelException
# Most usable class types
TypeString= "".__class__
# 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
#__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:
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]
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] ) )
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())))
data.anydata = "any value"
data.anydata = True
- print data.integerdata
+ print(data.integerdata)
return True
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)
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():
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():
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():
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():
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():
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")
# \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
## 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.
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
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")
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
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 enumarate.
in this enumarate.
@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.
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():
'SEP',
'OTHER'
])
- print TYPES_LIST.listvalues()
+ print(TYPES_LIST.listvalues())
return True
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:
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:
'MED',
'SMESH'])
- print "VISU in enumerate?", codes.contains("VISU")
+ print("VISU in enumerate?", codes.contains("VISU"))
if (not codes.contains("VISU")):
return True
else:
'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:
'MED',
'SMESH'], offset=20)
- print codes.listvalues()
+ print(codes.listvalues())
if codes.listvalues() != [20, 21, 22, 23, 24]:
return False
return True
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")
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
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
:return: the newly created SObject.
"""
- studyId = fatherSobj.GetStudy()._get_StudyId()
- editor = getStudyEditor(studyId)
+ editor = getStudyEditor()
sobj = editor.createItem(fatherSobj,
name = name,
icon = icon,
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)
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
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
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():
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)
# 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:
"""
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
obj = salome.naming_service.Resolve('Kernel/ModulCatalog')
catalog = obj._narrow(SALOME_ModuleCatalog.ModuleCatalog)
if not catalog:
- raise RuntimeError, "Can't accesss module catalog"
+ raise RuntimeError("Can't accesss 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
#
"""
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' )
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")
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 <b> salome.myStudyId </b>
-# 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.
"""
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.
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
# \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)
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
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
## 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.
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.
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.
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.
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.
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.
value `value`.
"""
attr = self.builder.FindOrCreateAttribute(sObject, "AttributePixMap")
- attr.SetPixMap(value.encode(ENCODING_FOR_SALOME_STUDY))
+ attr.SetPixMap(value)
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):
callback(pathname, **kwargs)
else:
# Unknown file type, print a message
- print 'Skipping %s' % pathname
+ print('Skipping %s' % pathname)
#
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)
return True
if __name__ == "__main__":
- import unittester
+ from . import unittester
unittester.run("syshelper", "TEST_findFiles")
unittester.run("syshelper", "TEST_walktree")
# 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
# \}
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!")
"""
"""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
__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):
# Basic use cases and unit tests
# ==============================================================================
#
-from uiexception import UiException
+from .uiexception import UiException
def TEST_getName():
testdata = TestData()
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():
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():
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():
ref_testdata.setName("The firts 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
# 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")
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()
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
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)
"""
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):
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):
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)
def myCallbackFunction():
- print "myCallbackFunction: the job is ended"
+ print("myCallbackFunction: the job is ended")
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()
__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
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")
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 bloc so that to display the exception in
the case where an exception is raised (usefull 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
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]
shared_imported[mname]=mod
# Salome modification end
- elif _partialModules.has_key(mname):
+ elif mname in _partialModules:
mod = _partialModules[mname]
# Salome modification start
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:
# Be sure to use the right module dictionnary
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__)
def createAndDisplayGO( *args, **kwargs ):
pass
-
#--------------------------------------------------------------------------
def UpdateViewer():
- pass
-
+ pass
#--------------------------------------------------------------------------
def setDisplayMode(objId, mode):
#--------------------------------------------------------------------------
-def Init(studyId):
+def Init():
return
#--------------------------------------------------------------------------
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
#--------------------------------------------------------------------------
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 mecanism available outside GUI"
+ print("SalomeOutsideGUI: no selection mecanism available outside GUI")
return 0
def getSelected(self, i):
"""Get the selection number i """
- print "SalomeOutsideGUI: no selection mecanism available outside GUI"
- return none
+ print("SalomeOutsideGUI: no selection mecanism 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.IsIncurentView: not available outside GUI"
+ print("SalomeOutsideGUI.IsIncurentView: 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 ""
#--------------------------------------------------------------------------
pass
def GetVariableNames(self):
- return self.kwargs.keys()
+ return list(self.kwargs.keys())
def IsVariable(self, variableName):
return variableName in self.kwargs
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):
pass
try:
aResult = eval(aResult)
- except Exception, e:
+ except Exception as e:
msg = str(e)
msg += "\n"
msg += "A problem occurs while parsing "
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()
exception
"""
import omniORB
-import cPickle
+import pickle
import SALOME
import Engines
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
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
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()
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):
return myObj
def ObjectToSObject(obj):
+ global myStudy
mySO = None
if obj is not None:
ior = orb.object_to_string(obj)
#--------------------------------------------------------------------------
-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()
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
#--------------------------------------------------------------------------
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, "<CanCopy> for "+theInfo+" returns false"
+ if not myStudy.CanCopy(theSO):
+ raise RuntimeError("<CanCopy> for "+theInfo+" returns false")
- if not myStudyManager.Copy(theSO):
- raise RuntimeError, "<Copy> for "+theInfo+" returns false"
+ if not myStudy.Copy(theSO):
+ raise RuntimeError("<Copy> for "+theInfo+" returns false")
- if not myStudyManager.CanPaste(theSO):
- raise RuntimeError, "<CanPaste> for "+theInfo+" returns false"
+ if not myStudy.CanPaste(theSO):
+ raise RuntimeError("<CanPaste> for "+theInfo+" returns false")
# check: before paste study is not changed check
- if aStudyPersist != PersistentPresentation(myStudy, aRoot, 1):
- raise RuntimeError, "Study is changed before Paste calling for "+theInfo
+ if aStudyPersist != PersistentPresentation(aRoot, 1):
+ raise RuntimeError("Study is changed before Paste calling for "+theInfo)
aSObj = theSO
if theComponentPaste:
aSObj = theSO.GetFatherComponent()
theInfo = theInfo + "(paste for component)"
- if myStudyManager.Paste(aSObj) == None:
- raise RuntimeError, "<Paste> for "+theInfo+" returns None object"
+ if myStudy.Paste(aSObj) == None:
+ raise RuntimeError("<Paste> for "+theInfo+" returns None object")
aNewTree = GetTree(aRoot)
aLen = len(aTree)
for a in range(0,aLen):
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")
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
-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())
#--------------------------------------------------------------------------
create new empty study if there is active study
<URL> (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
# 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
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 accesss module catalog"
-print "OK"
+ raise RuntimeError("Can't accesss module catalog")
+print("OK")
-print
+print()
-print "======================================================================"
-print " %d. Check modules availability in the module catalog " % step; step+=1
-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
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
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" );
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
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")
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)
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();
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 )
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;
}
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 = "<<myTestStudyId);
+ // The study with properties was opened
+ LOG("TestComponentImpl::testkernel: study with properties was opened");
return true;
}
int main (int argc, char * argv[]) {
TEST_corba();
TEST_getLifeCycleCORBA();
- TEST_getStudyManager();
+ TEST_getStudy();
TEST_getSalomeLauncher();
return 0;
}
};
//===========================================================================
- SALOMEDS::SObject_ptr SALOMEDS_DriverDefaultImpl::PublishInStudy(SALOMEDS::Study_ptr theStudy,
- SALOMEDS::SObject_ptr theSObject,
- CORBA::Object_ptr theObject,
- const char* theName)
+ SALOMEDS::SObject_ptr SALOMEDS_DriverDefaultImpl::PublishInStudy(SALOMEDS::SObject_ptr theSObject,
+ CORBA::Object_ptr theObject,
+ const char* theName)
throw (SALOME::SALOME_Exception)
{
MESSAGE("-----------------------------------------");
virtual bool CanPublishInStudy(CORBA::Object_ptr theIOR);
- virtual SALOMEDS::SObject_ptr PublishInStudy
- (SALOMEDS::Study_ptr theStudy,
- SALOMEDS::SObject_ptr theSObject,
- CORBA::Object_ptr theObject,
- const char* theName)
- throw (SALOME::SALOME_Exception);
+ virtual SALOMEDS::SObject_ptr PublishInStudy(SALOMEDS::SObject_ptr theSObject,
+ CORBA::Object_ptr theObject,
+ const char* theName)
+ throw (SALOME::SALOME_Exception);
virtual CORBA::Boolean CanCopy(SALOMEDS::SObject_ptr theObject);
/**
- * This returns a static reference to the SALOME study manager. The
- * study manager can be used to retrieve a study or to get
- * informations about a study.
+ * This returns a static reference to the SALOME study. The
+ * study can be used to get informations about it.
*/
- SALOMEDS::StudyManager_ptr getStudyManager() {
- static SALOMEDS::StudyManager_ptr aStudyManager;
- if(CORBA::is_nil(aStudyManager)){
+ SALOMEDS::Study_ptr getStudyServant() {
+ static SALOMEDS::Study_ptr aStudy;
+ if(CORBA::is_nil(aStudy)){
SALOME_NamingService *aNamingService = getNamingService();
- CORBA::Object_ptr anObject = aNamingService->Resolve("/myStudyManager");
- aStudyManager = SALOMEDS::StudyManager::_narrow(anObject);
+ CORBA::Object_ptr anObject = aNamingService->Resolve("/Study");
+ aStudy = SALOMEDS::Study::_narrow(anObject);
}
- return aStudyManager;
+ return aStudy;
}
/**
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.
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();
// 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);
/** 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) {
}
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();
}
}
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) {
class KERNELHELPERS_EXPORT SALOME_StudyEditor {
public:
- SALOME_StudyEditor(int studyId);
- SALOME_StudyEditor(SALOMEDS::Study_ptr study);
+ SALOME_StudyEditor();
typedef std::vector<SALOMEDS::SObject_ptr> SObjectList;
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;
};
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 = "<<myTestStudyId);
+ // The study with properties was opened
+ LOG("TestComponentImpl::testkernel: study with properties was opened");
}
void KernelHelpersUnitTests::TEST_getSalomeLauncher() {
CPPUNIT_TEST_SUITE( KernelHelpersUnitTests );
CPPUNIT_TEST( TEST_corba );
CPPUNIT_TEST( TEST_getLifeCycleCORBA );
- CPPUNIT_TEST( TEST_getStudyManager );
+ CPPUNIT_TEST( TEST_getStudy );
CPPUNIT_TEST( TEST_getSalomeLauncher );
CPPUNIT_TEST_SUITE_END();
void TEST_corba();
void TEST_getLifeCycleCORBA();
- void TEST_getStudyManager();
+ void TEST_getStudy();
void TEST_getSalomeLauncher();
};
# 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
text = f.read()
f.close()
self.assertEqual(text, content)
- except IOError,ex:
+ except IOError as ex:
self.fail("IO exception:" + str(ex));
##############################
launcher = salome.naming_service.Resolve('/SalomeLauncher')
for resource in self.ressources:
- print "Testing python_salome job on ", resource
+ print("Testing python_salome job on ", resource)
job_params.result_directory = local_result_dir + resource
job_params.job_name = "PyJob" + resource
job_params.resource_required.name = resource
launcher.launchJob(job_id)
jobState = launcher.getJobState(job_id)
- 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")
resManager= salome.lcc.getResourcesManager()
for resource in self.ressources:
- print "Testing command job on ", resource
+ print("Testing command job on ", resource)
job_params.result_directory = local_result_dir + resource
job_params.job_name = "CommandJob_" + resource
job_params.resource_required.name = resource
launcher.launchJob(job_id)
# wait for the end of the job
jobState = launcher.getJobState(job_id)
- print "Job %d state: %s" % (job_id,jobState)
+ print("Job %d state: %s" % (job_id,jobState))
while jobState != "FINISHED" and jobState != "FAILED" :
time.sleep(3)
jobState = launcher.getJobState(job_id)
- print "Job %d state: %s" % (job_id,jobState)
+ print("Job %d state: %s" % (job_id,jobState))
pass
# verify the results
# job script
script_text = """<?xml version='1.0' encoding='iso-8859-1' ?>
<proc name="newSchema_1">
- <property name="DefaultStudyID" value="1"/>
<container name="DefaultContainer">
<property name="container_kind" value="Salome"/>
<property name="attached_on_cloning" value="0"/>
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
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")
# job script
script_text = """<?xml version='1.0' encoding='iso-8859-1' ?>
<proc name="myschema">
- <property name="DefaultStudyID" value="1"/>
<type name="string" kind="string"/>
<type name="bool" kind="bool"/>
<type name="double" kind="double"/>
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
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")
*
* \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();
Engines::EngineComponent_var compo = _FindComponent(new_params,
componentName,
- studyId,
listOfResources);
return compo._retn();
*
* \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
new_params.resource_params.resList = listOfResources;
Engines::EngineComponent_var compo = _LoadComponent(new_params,
- componentName,
- studyId);
+ componentName);
return compo._retn();
}
*
* \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::
FindOrLoad_Component(const Engines::ContainerParameters& params,
- const char *componentName,
- int studyId)
+ const char *componentName)
{
// --- Check if Component Name is known in ModuleCatalog
}
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();
// 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)
{
std::string portNumber (::getenv ("NSPORT") );
std::string python_exe;
- python_exe = std::string("python");
+ python_exe = std::string("python3");
if ( !portNumber.empty() )
{
*
* \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
*/
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
*
* \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
*/
//=============================================================================
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));
CORBA::string_free(reason);
Engines::EngineComponent_var myInstance =
- cont->create_component_instance(componentName, studyId);
+ cont->create_component_instance(componentName);
return myInstance._retn();
}
*
* \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");
// @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();
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,
// Parallel extension
Engines::EngineComponent_ptr
Load_ParallelComponent(const Engines::ContainerParameters& params,
- const char *componentName,
- int studyId);
+ const char *componentName);
bool isKnownComponentClass(const char *componentName);
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;
# 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
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}
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
# Module : SALOME
# $Header$
#
-import sys, os,signal,string,commands
+import sys, os,signal,string,subprocess
import subprocess
import runSalome
import setenv
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
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()
enginePy=lcc.FindComponent(myContainerparamsPy,'SALOME_TestComponentPy')
enginePy.Coucou(1)
except :
- print 'ContainerManager.FindOrStartContainer( myContainerparams , computerlist ) Python failed'
+ print('ContainerManager.FindOrStartContainer( myContainerparams , computerlist ) Python failed')
#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 <hold_lock> 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 <hold_lock> is true, caller holds the Python interpreter lock.
-
-
- omniORBpyAPI();
- // Constructor for the singleton. Sets up the function pointers.
-};
-
-omniORBpyAPI* api;
+#include <Python.h>
+#include <omniORBpy.h>
+omniORBpyAPI* api=0;
%}
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);
%}
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"
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)
# 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
port = getCurrentPort()
try:
from PortManager import releasePort
- print "### release current port:", port
+ print("### release current port:", port)
releasePort(port)
except:
pass
"""
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):
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
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;
// 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)
{
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++)
}
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;
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);
{
void* handle = _library_map[impl_name];
iobject = createMPIInstance(genericRegisterName,
- handle,
- studyId);
+ handle);
return iobject._retn();
}
Engines::EngineComponent_ptr
Engines_MPIContainer_i::createMPIInstance(std::string genericRegisterName,
- void *handle,
- int studyId)
+ void *handle)
{
Engines::EngineComponent_var iobject;
Engines::MPIObject_var pobj;
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<Engines_Component_i*>(_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)
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;
}
Engines::IORTab* tior;
std::string compoName;
std::string nameToRegister;
- long studyId;
Engines::EngineComponent_ptr cptr;
} thread_st;
// 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);
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
//----------------------------------------------------------------------
// Function : SALOME_ModuleCatalog_AcomponentImpl
// Purpose : Constructor
-// Affect the component name, type,icone, a bool to define
-// if it's multistudy or not.
+// Affect the component name, type,icone
// Affect too the constraint and the interfaces of the component
// and the pathes prefixes for all computers
//----------------------------------------------------------------------
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
*/
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
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());
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";
_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;
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;
std::string name;
std::string username;
ParserComponentType type;
- bool multistudy;
std::string icon;
std::string constraint;
ParserInterfaces interfaces;
<< " 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;
{
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")
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
"COMP_TYPE" : "",
"COMP_NAME" : "",
"COMP_UNAME" : "",
- "COMP_MULT" : "",
"COMP_IMPL" : ""
}
# print error message
#--------------------------------------------------
def error (message):
- print "ERROR : ", message
+ print("ERROR : ", message)
#--------------------------------------------------
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 != '':
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)
## 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())
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)
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')
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:
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):
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):
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)
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')
if ((CatalogFileName_old != "") & os.path.exists(CatalogFileName_old)):
os.unlink(CatalogFileName_old)
- print
+ print()
if __name__ == "__main__":
- print
- print "Usage : omniidl -bIDLparser [-I<catalog files directory>]* -Wbcatalog=<my_catalog.xml>[,icon=<pngfile>][,version=<num>][,author=<name>][,name=<component_name>][,username=<component_username>][,multistudy=<component_multistudy>][,impltype=<implementation type : 0 (python), 1 (C++)>] <file.idl>"
- print
+ print()
+ print("Usage : omniidl -bIDLparser [-I<catalog files directory>]* -Wbcatalog=<my_catalog.xml>[,icon=<pngfile>][,version=<num>][,author=<name>][,name=<component_name>][,username=<component_username>][,impltype=<implementation type : 0 (python), 1 (C++)>] <file.idl>")
+ print()
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(
#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
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" )
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)
_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):
#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):
#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" )
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=[]
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):
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)
# 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
// 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"
extern bool _Sleeping ;
static Engines_Parallel_Component_i * theEngines_Component ;
-bool Engines_Parallel_Component_i::_isMultiStudy = true;
bool Engines_Parallel_Component_i::_isMultiInstance = false;
//=============================================================================
_Executed(false) ,
_graphName("") ,
_nodeName(""),
- _studyId(-1),
_destroyed(false),
_CanceledThread(false)
{
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
return dynamic_cast<Engines_Parallel_Container_i*>(_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
*/
//=============================================================================
-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;
// 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_
void ping();
void destroy();
- CORBA::Long getStudyId();
Engines::Container_ptr GetContainerRef();
void setProperties(const Engines::FieldsDict& dico);
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);
// 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);
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 ;
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;
}
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;
}
// 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("");
_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 !
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;
{
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)
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);
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;
* 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;
}
* 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
*/
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__
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();
* 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<std::string,Engines::EngineComponent_var>::iterator itm =_listInstances_map.begin();
if (instance.find(registeredName) == 0)
{
anEngine = (*itm).second;
- if (studyId == anEngine->getStudyId())
- {
- return anEngine._retn();
- }
+ return anEngine._retn();
}
itm++;
}
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<Engines_Component_i*>(_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 (...)
* 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:
*/
//=============================================================================
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();
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);
* 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:
//=============================================================================
Engines::EngineComponent_ptr
Engines_Parallel_Container_i::createCPPInstance(std::string genericRegisterName,
- void *handle,
- int studyId)
+ void *handle)
{
MESSAGE("Entering Engines_Parallel_Container_i::createCPPInstance");
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<Engines_Component_i*>(_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)
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;
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))
// 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_
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);
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,
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();
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);
_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<std::string, PortableServer::ObjectId *> _par_obj_inst_map;
typedef PortableServer::ObjectId * (*FACTORY_FUNCTION) (CORBA::ORB_ptr, char *, int,
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
SALOMEDS_UseCaseBuilder.cxx
SALOMEDS_StudyBuilder.cxx
SALOMEDS_Study.cxx
- SALOMEDS_StudyManager.cxx
SALOMEDS_AttributeStudyProperties.cxx
SALOMEDS_AttributeComment.cxx
SALOMEDS_AttributeDrawable.cxx
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
// $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 "SALOMEDS_Defines.hxx"
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)
//=============================================================================
/*!
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_StudyManager_i * aStudyManager_i = new SALOMEDS_StudyManager_i(orb, root_poa);
- // Activate the objects. This tells the POA that the objects are ready to accept requests.
- PortableServer::ObjectId_var aStudyManager_iid = root_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");
+ SALOMEDS_EXPORT
+ void CreateStudy(CORBA::ORB_ptr orb, PortableServer::POA_ptr root_poa)
+ {
+ SALOME_NamingService namingService(orb);
+ CORBA::Object_var obj = namingService.Resolve( "/Study" );
+ SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( obj );
+ if( CORBA::is_nil(aStudy) ) {
+ 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();
+ }
}
//
#include <SALOMEconfig.h>
#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"
* 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;
MESSAGE(" ");
MESSAGE("*Reference"<<RefSO->GetID());
}
- DumpComponent(Study,CSO,offset+2);
+ DumpComponent(CSO,offset+2);
}
}
* 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 "<<name);
- DumpComponent(Study,SC,offset);
+ DumpComponent(SC,offset);
}
}
* Purpose :
*/
//============================================================================
-static void Test(SALOMEDS::StudyManager_ptr myStudyMgr )
+static void Test()
{
try {
char* name;
- MESSAGE("Create New Study Study1");
- SALOMEDS::Study_var myStudy = myStudyMgr->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;
Name->SetValue("mesh_cylinder_0");
StudyBuild->CommitCommand();
- MESSAGE("Test GetStudy");
- SALOMEDS::Study_var stu = mesh_cylinder->GetStudy();
- MESSAGE ("-> Study Name is "<<stu->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 "<<name);
+ MESSAGE("-> ComponentDataType is "<<name);
-
// FindComponentID Test
- SALOMEDS::SComponent_var compo1 = myStudy1->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 "<<name);
-
+ MESSAGE("-> ComponentDataType is "<<name);
+
// FindObject Test
- SALOMEDS::SObject_var objn = myStudy1->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")) {
}
// 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")) {
else {
MESSAGE("-> Name is not found");
}
- //DumpStudy(myStudy1);
+ //DumpStudy();
}
catch(HDFexception)
{
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();
#include "SALOMEDS_Study_i.hxx"
#include "SALOMEDS.hxx"
#include <SALOMEDSImpl_IParameters.hxx>
+#include <SALOME_KernelServices.hxx>
#include <stdlib.h>
#include CORBA_CLIENT_HEADER(SALOME_Session)
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();
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);
//
#include "SALOMEDS_IParameters.hxx"
+#include <SALOMEDSClient_ClientFactory.hxx>
+#include <SALOME_KernelServices.hxx>
#include <utilities.h>
#define PT_INTEGER 0
{
if(!ap) return;
_ap = ap;
- _PTR(SObject) so = _ap->GetSObject();
- _study = so->GetStudy();
}
SALOMEDS_IParameters::~SALOMEDS_IParameters()
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;
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_);
/*!
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.
private:
_PTR(AttributeParameter) _ap;
- _PTR(Study) _study;
std::map<std::string, std::string> _compNames;
};
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;
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();
#include "SALOMEDS_SObject_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"
}
}
_orb = CORBA::ORB::_duplicate(orb);
- //SALOME::GenericObj_i::myPOA = SALOMEDS_StudyManager_i::GetPOA(GetStudy());
}
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
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();
#include "Utils_SINGLETON.hxx"
#include "SALOME_NamingService.hxx"
-#include "SALOMEDS_StudyManager_i.hxx"
+#include "SALOMEDS_Study_i.hxx"
#include <SALOMEconfig.h>
#include CORBA_SERVER_HEADER(SALOMEDS)
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;
if(EnvL==1)
{
CORBA::ORB_var orb1 = CORBA::ORB_init(argc,argv) ;
- SALOME_NamingService &NS = *SINGLETON_<SALOME_NamingService>::Instance() ;
- NS.init_orb( orb1 ) ;
+ NS = SINGLETON_<SALOME_NamingService>::Instance() ;
+ NS->init_orb( orb1 ) ;
for(int j=1; j<=NumberOfTries; j++)
{
if (j!=1)
// 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_<SALOME_NamingService>::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.
#include "SALOMEDSImpl_GenericVariable.hxx"
#include "SALOMEDSImpl_UseCaseBuilder.hxx"
+#include <SALOME_KernelServices.hxx>
+
#include "SALOMEDS_Driver_i.hxx"
#include "SALOMEDS_Study_i.hxx"
_isLocal = true;
_local_impl = theStudy;
_corba_impl = SALOMEDS::Study::_nil();
- init_orb();
+ InitORB();
}
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_<ORB_INIT>::Instance();
+ ASSERT(SINGLETON_<ORB_INIT>::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<SALOMEDS_SObject*>(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<SALOMEDS_SObject*>(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<SALOMEDS_SObject*>(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<SALOMEDS_SObject*>(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;
}
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<std::string> SALOMEDS_Study::GetObjectNames(const std::string& theContext)
-{
- std::vector<std::string> 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<std::string> SALOMEDS_Study::GetDirectoryNames(const std::string& theContext)
-{
- std::vector<std::string> 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<std::string> SALOMEDS_Study::GetFileNames(const std::string& theContext)
-{
- std::vector<std::string> 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<std::string> SALOMEDS_Study::GetComponentNames(const std::string& theContext)
-{
- std::vector<std::string> 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<SALOMEDS_SObject*>(theSO.get());
SALOMEDS::Locker lock;
aName = _local_impl->Name();
}
- else aName = _corba_impl->Name();
+ else aName = Kernel_Utils::encode_s(_corba_impl->Name());
return aName;
}
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()
SALOMEDS::Locker lock;
aURL = _local_impl->URL();
}
- else aURL = _corba_impl->URL();
+ else
+ aURL = Kernel_Utils::encode_s(_corba_impl->URL());
return aURL;
}
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)
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);
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)
return _orb->string_to_object(theIOR.c_str());
}
-void SALOMEDS_Study::init_orb()
-{
- ORB_INIT &init = *SINGLETON_<ORB_INIT>::Instance() ;
- ASSERT(SINGLETON_<ORB_INIT>::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;
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);
}
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);
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<std::string> GetObjectNames(const std::string& theContext);
- virtual std::vector<std::string> GetDirectoryNames(const std::string& theContext);
- virtual std::vector<std::string> GetFileNames(const std::string& theContext);
- virtual std::vector<std::string> GetComponentNames(const std::string& theContext);
virtual _PTR(ChildIterator) NewChildIterator(const _PTR(SObject)& theSO);
virtual _PTR(SComponentIterator) NewComponentIterator();
virtual _PTR(StudyBuilder) NewBuilder();
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<std::string> 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);
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
#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"
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;
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);
_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 :
*/
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);
+++ /dev/null
-// 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 <process.h>
-#else
-#include <sys/types.h>
-#include <unistd.h>
-#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<SALOMEDSImpl_StudyManager*>(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<SALOMEDSImpl_StudyManager*>(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<std::string> SALOMEDS_StudyManager::GetOpenStudies()
-{
- std::vector<std::string> aVector;
- int aLength, i;
-
- if (_isLocal) {
- SALOMEDS::Locker lock;
-
- std::vector<SALOMEDSImpl_Study*> 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<SALOMEDS_SObject*>(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<SALOMEDS_SObject*>(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<SALOMEDS_SObject*>(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<SALOMEDS_SObject*>(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_<ORB_INIT>::Instance();
- ASSERT(SINGLETON_<ORB_INIT>::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;
-}
+++ /dev/null
-// 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 <vector>
-#include <string>
-
-#include "SALOMEDSClient.hxx"
-#include "SALOMEDSImpl_StudyManager.hxx"
-
-// IDL headers
-
-#include <SALOMEconfig.h>
-#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<std::string> 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
+++ /dev/null
-// 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 <sstream>
-#include <vector>
-#include <map>
-
-#ifdef WIN32
-#include <process.h>
-#else
-#include <sys/types.h>
-#include <unistd.h>
-#endif
-
-UNEXPECT_CATCH(SalomeException,SALOME::SALOME_Exception);
-UNEXPECT_CATCH(LockProtection, SALOMEDS::StudyBuilder::LockProtection);
-
-static SALOMEDS_Driver_i* GetDriver(const SALOMEDSImpl_SObject& theObject, CORBA::ORB_ptr orb);
-
-static std::map<int, PortableServer::POA_ptr> _mapOfPOA;
-
-//============================================================================
-/*! Function : SALOMEDS_StudyManager_i
- * Purpose : SALOMEDS_StudyManager_i constructor
- */
-//============================================================================
-SALOMEDS_StudyManager_i::SALOMEDS_StudyManager_i(CORBA::ORB_ptr orb, PortableServer::POA_ptr thePOA)
-{
- _orb = CORBA::ORB::_duplicate(orb);
- _poa = PortableServer::POA::_duplicate(thePOA);
- _name_service = new SALOME_NamingService(_orb);
- // Study directory creation in the naming service : to register all
- // open studies in the session
- _name_service->Create_Directory("/Study");
- _impl = new SALOMEDSImpl_StudyManager;
- _factory = new SALOMEDS_DriverFactory_i(_orb);
-}
-
-//============================================================================
-/*! Function : ~SALOMEDS_StudyManager_i
- * Purpose : SALOMEDS_StudyManager_i destructor
- */
-//============================================================================
-SALOMEDS_StudyManager_i::~SALOMEDS_StudyManager_i()
-{
- // Destroy directory to register open studies
- _name_service->Destroy_Directory("/Study");
- delete _name_service;
- delete _factory;
- delete _impl;
-}
-
-//============================================================================
-/*! Function : register_name
- * Purpose : Register the study Manager in the naming service under the
- * context name
- */
-//============================================================================
-void SALOMEDS_StudyManager_i::register_name(const char * name)
-{
- SALOMEDS::StudyManager_var aManager(_this());
- _name_service->Register(aManager.in(), name);
-}
-
-
-//============================================================================
-/*! Function : NewStudy
- * Purpose : Create a New Study of name study_name
- */
-//============================================================================
-SALOMEDS::Study_ptr SALOMEDS_StudyManager_i::NewStudy(const char* study_name)
- throw(SALOME::SALOME_Exception)
-{
- SALOMEDS::Locker lock;
-
-#ifndef ALLOW_MULTI_STUDIES
- std::vector<SALOMEDSImpl_Study*> anOpened = _impl->GetOpenStudies();
- int aLength = anOpened.size();
-
- if(aLength)
- {
- MESSAGE("There is already an active study in this session. Launch a new session, or close the study");
- THROW_SALOME_CORBA_EXCEPTION("Problem on New Study.\nThere is already an active study in this session.\nLaunch a new session, or close the study", SALOME::BAD_PARAM)
- }
-#endif // !ALLOW_MULTI_STUDIES
-
- SALOMEDSImpl_Study* aStudyImpl = _impl->NewStudy(study_name);
- if(!aStudyImpl) {
- MESSAGE("NewStudy : Error : " << _impl->GetErrorCode());
- return SALOMEDS::Study::_nil();
- }
-
- MESSAGE("NewStudy : Creating the CORBA servant holding it... ");
-
- SALOMEDS_Study_i *Study_servant = SALOMEDS_Study_i::GetStudyServant(aStudyImpl, _orb);
- PortableServer::ObjectId_var servantid = _poa->activate_object(Study_servant); // to use poa registered in _mapOfPOA
- SALOMEDS::Study_var Study = Study_servant->_this();
-
- // Register study in the naming service
- // Path to acces the study
- if(!_name_service->Change_Directory("/Study"))
- MESSAGE( "Unable to access the study directory" )
- else
- _name_service->Register(Study, study_name);
-
- // Assign the value of the IOR in the study->root
- CORBA::String_var IORStudy = _orb->object_to_string(Study);
-
- aStudyImpl->SetTransientReference((char*)IORStudy.in());
-
- _mapOfPOA[Study->StudyId()] = _poa;
-
- return Study._retn();
-}
-
-//============================================================================
-/*! Function : Open
- * Purpose : Open a Study from it's persistent reference
- */
-//============================================================================
-SALOMEDS::Study_ptr SALOMEDS_StudyManager_i::Open(const char* aUrl)
- throw(SALOME::SALOME_Exception)
-{
- SALOMEDS::Locker lock;
-
- Unexpect aCatch(SalomeException);
- MESSAGE("Begin of SALOMEDS_StudyManager_i::Open");
-
- #ifndef ALLOW_MULTI_STUDIES
- std::vector<SALOMEDSImpl_Study*> anOpened = _impl->GetOpenStudies();
- int aLength = anOpened.size();
-
- if(aLength)
- {
- MESSAGE("There is already an active study in this session. Launch a new session, or close the study.");
- THROW_SALOME_CORBA_EXCEPTION("Problem on Open Study.\nThere is already an active study in this session.\nLaunch a new session, or close the study.", SALOME::BAD_PARAM)
- }
-#endif // ;ALLOW_MULTI_STUDIES
-
- SALOMEDSImpl_Study* aStudyImpl = _impl->Open(std::string(aUrl));
-
- if ( !aStudyImpl )
- THROW_SALOME_CORBA_EXCEPTION("Impossible to Open study from file", SALOME::BAD_PARAM)
-
- MESSAGE("Open : Creating the CORBA servant holding it... ");
-
- // Temporary aStudyUrl in place of study name
- SALOMEDS_Study_i * Study_servant = SALOMEDS_Study_i::GetStudyServant(aStudyImpl, _orb);
- PortableServer::ObjectId_var servantid = _poa->activate_object(Study_servant); // to use poa register in _mapOfPOA
- SALOMEDS::Study_var Study = Study_servant->_this();
-
- // Assign the value of the IOR in the study->root
- CORBA::String_var IORStudy = _orb->object_to_string(Study);
- aStudyImpl->SetTransientReference((char*)IORStudy.in());
-
- _mapOfPOA[Study->StudyId()] = _poa;
-
- // Register study in the naming service
- // Path to acces the study
- if(!_name_service->Change_Directory("/Study")) MESSAGE( "Unable to access the study directory" )
- else _name_service->Register(Study, aStudyImpl->Name().c_str());
-
- return Study._retn();
-}
-
-
-
-//============================================================================
-/*! Function : Close
- * Purpose : Close a study.
- * If the study hasn't been saved, ask the user to confirm the
- * close action without saving
- */
-//============================================================================
-void SALOMEDS_StudyManager_i::Close(SALOMEDS::Study_ptr aStudy)
-{
- SALOMEDS::Locker lock;
-
- if(aStudy->_is_nil()) return;
-
- // Destroy study name in the naming service
- if(_name_service->Change_Directory("/Study")){
- CORBA::String_var aString(aStudy->Name());
- _name_service->Destroy_Name(aString.in());
- }
-
- SALOMEDS::unlock();
- aStudy->Close();
- SALOMEDS::lock();
-
- //remove study servant
- PortableServer::POA_ptr poa=GetPOA(aStudy);
- PortableServer::ServantBase* aservant=poa->reference_to_servant(aStudy);
- PortableServer::ObjectId_var anObjectId = poa->servant_to_id(aservant);
- poa->deactivate_object(anObjectId.in());
- aservant->_remove_ref(); // decrement for the call to reference_to_servant
- aservant->_remove_ref(); // to delete the object
-}
-
-//============================================================================
-/*! Function : Save
- * Purpose : Save a Study to it's persistent reference
- */
-//============================================================================
-CORBA::Boolean SALOMEDS_StudyManager_i::Save(SALOMEDS::Study_ptr aStudy, CORBA::Boolean theMultiFile)
-{
- SALOMEDS::Locker lock;
-
- if(aStudy->_is_nil()) {
- MESSAGE("Save error: Study is null");
- return false;
- }
-
- SALOMEDSImpl_Study* aStudyImpl = _impl->GetStudyByID(aStudy->StudyId());
- return _impl->Save(aStudyImpl, _factory, theMultiFile);
-}
-
-CORBA::Boolean SALOMEDS_StudyManager_i::SaveASCII(SALOMEDS::Study_ptr aStudy, CORBA::Boolean theMultiFile)
-{
- SALOMEDS::Locker lock;
-
- if(aStudy->_is_nil()) {
- MESSAGE("SaveASCII error: Study is null");
- return false;
- }
-
- SALOMEDSImpl_Study* aStudyImpl = _impl->GetStudyByID(aStudy->StudyId());
- return _impl->SaveASCII(aStudyImpl, _factory, theMultiFile);
-}
-
-//=============================================================================
-/*! Function : SaveAs
- * Purpose : Save a study to the persistent reference aUrl
- */
-//============================================================================
-CORBA::Boolean SALOMEDS_StudyManager_i::SaveAs(const char* aUrl, SALOMEDS::Study_ptr aStudy, CORBA::Boolean theMultiFile)
-{
- SALOMEDS::Locker lock;
-
- if(aStudy->_is_nil()) {
- MESSAGE("SaveASCII error: Study is null");
- return false;
- }
-
- SALOMEDSImpl_Study* aStudyImpl = _impl->GetStudyByID(aStudy->StudyId());
- return _impl->SaveAs(std::string(aUrl), aStudyImpl, _factory, theMultiFile);
-}
-
-CORBA::Boolean SALOMEDS_StudyManager_i::SaveAsASCII(const char* aUrl, SALOMEDS::Study_ptr aStudy, CORBA::Boolean theMultiFile)
-{
- SALOMEDS::Locker lock;
-
- if(aStudy->_is_nil()) {
- MESSAGE("SaveASCII error: Study is null");
- return false;
- }
-
- SALOMEDSImpl_Study* aStudyImpl = _impl->GetStudyByID(aStudy->StudyId());
- return _impl->SaveAsASCII(std::string(aUrl), aStudyImpl, _factory, theMultiFile);
-}
-
-//============================================================================
-/*! Function : GetOpenStudies
- * Purpose : Get name list of open studies in the session
- */
-//============================================================================
-SALOMEDS::ListOfOpenStudies* SALOMEDS_StudyManager_i::GetOpenStudies()
-{
- SALOMEDS::Locker lock;
-
- std::vector<SALOMEDSImpl_Study*> anOpened = _impl->GetOpenStudies();
- int aLength = anOpened.size();
-
- SALOMEDS::ListOfOpenStudies_var _list_open_studies = new SALOMEDS::ListOfOpenStudies;
- _list_open_studies->length(aLength);
-
- if(!aLength)
- {
- MESSAGE("No active study in this session");
- }
- else
- {
- for (unsigned int ind=0; ind < aLength; ind++)
- {
- _list_open_studies[ind] = CORBA::string_dup(anOpened[ind]->Name().c_str());
- SCRUTE(_list_open_studies[ind]) ;
- }
- }
- return _list_open_studies._retn();
-}
-
-//============================================================================
-/*! Function : GetStudyByName
- * Purpose : Get a study from its name
- */
-//============================================================================
-SALOMEDS::Study_ptr SALOMEDS_StudyManager_i::GetStudyByName(const char* aStudyName)
-{
- SALOMEDS::Locker lock;
-
- SALOMEDSImpl_Study* aStudyImpl = _impl->GetStudyByName(std::string(aStudyName));
-
- if (!aStudyImpl)
- {
- MESSAGE(_impl->GetErrorCode().c_str());
- return SALOMEDS::Study::_nil();
- }
-
- SALOMEDS_Study_i* aStudy_servant = SALOMEDS_Study_i::GetStudyServant(aStudyImpl, _orb);
- return aStudy_servant->_this();
-}
-
-//============================================================================
-/*! Function : GetStudyByID
- * Purpose : Get a study from its ID
- */
-//============================================================================
-SALOMEDS::Study_ptr SALOMEDS_StudyManager_i::GetStudyByID(CORBA::Short aStudyID)
-{
- SALOMEDS::Locker lock;
-
- SALOMEDSImpl_Study* aStudyImpl = _impl->GetStudyByID(aStudyID);
-
- if (!aStudyImpl)
- {
- MESSAGE(_impl->GetErrorCode().c_str());
- return SALOMEDS::Study::_nil();
- }
-
- SALOMEDS_Study_i* aStudy_servant = SALOMEDS_Study_i::GetStudyServant(aStudyImpl, _orb);
- return aStudy_servant->_this();
-}
-
-
-//============================================================================
-/*! Function : CanCopy
- * Purpose :
- */
-//============================================================================
-CORBA::Boolean SALOMEDS_StudyManager_i::CanCopy(SALOMEDS::SObject_ptr theObject)
-{
- SALOMEDS::Locker lock;
-
- SALOMEDS::Study_var aStudy = theObject->GetStudy();
- SALOMEDSImpl_Study* aStudyImpl = _impl->GetStudyByID(aStudy->StudyId());
- CORBA::String_var anID = theObject->GetID();
- SALOMEDSImpl_SObject anObject = aStudyImpl->GetSObject(anID.in());
-
- SALOMEDS_Driver_i* aDriver = GetDriver(anObject, _orb);
- bool ret = _impl->CanCopy(anObject, aDriver);
- delete aDriver;
- return ret;
-}
-
-//============================================================================
-/*! Function : Copy
- * Purpose :
- */
-//============================================================================
-CORBA::Boolean SALOMEDS_StudyManager_i::Copy(SALOMEDS::SObject_ptr theObject)
-{
- SALOMEDS::Locker lock;
-
- SALOMEDS::Study_var aStudy = theObject->GetStudy();
- SALOMEDSImpl_Study* aStudyImpl = _impl->GetStudyByID(aStudy->StudyId());
- CORBA::String_var anID = theObject->GetID();
- SALOMEDSImpl_SObject anObject = aStudyImpl->GetSObject(anID.in());
-
- SALOMEDS_Driver_i* aDriver = GetDriver(anObject, _orb);
- bool ret = _impl->Copy(anObject, aDriver);
- delete aDriver;
- return ret;
-}
-
-//============================================================================
-/*! Function : CanPaste
- * Purpose :
- */
-//============================================================================
-CORBA::Boolean SALOMEDS_StudyManager_i::CanPaste(SALOMEDS::SObject_ptr theObject)
-{
- SALOMEDS::Locker lock;
-
- SALOMEDS::Study_var aStudy = theObject->GetStudy();
- SALOMEDSImpl_Study* aStudyImpl = _impl->GetStudyByID(aStudy->StudyId());
- CORBA::String_var anID = theObject->GetID();
- SALOMEDSImpl_SObject anObject = aStudyImpl->GetSObject(anID.in());
-
- SALOMEDS_Driver_i* aDriver = GetDriver(anObject, _orb);
- bool ret = _impl->CanPaste(anObject, aDriver);
- delete aDriver;
- return ret;
-}
-
-//============================================================================
-/*! Function : Paste
- * Purpose :
- */
-//============================================================================
-SALOMEDS::SObject_ptr SALOMEDS_StudyManager_i::Paste(SALOMEDS::SObject_ptr theObject)
- throw(SALOMEDS::StudyBuilder::LockProtection)
-{
- SALOMEDS::Locker lock;
-
- Unexpect aCatch(LockProtection);
- SALOMEDS::Study_var aStudy = theObject->GetStudy();
-
- SALOMEDSImpl_Study* aStudyImpl = _impl->GetStudyByID(aStudy->StudyId());
- CORBA::String_var anID = theObject->GetID();
- SALOMEDSImpl_SObject anObject = aStudyImpl->GetSObject(anID.in());
- SALOMEDSImpl_SObject aNewSO;
-
- try {
- SALOMEDS_Driver_i* aDriver = GetDriver(anObject, _orb);
- aNewSO = _impl->Paste(anObject, aDriver);
- delete aDriver;
- }
- catch (...) {
- throw SALOMEDS::StudyBuilder::LockProtection();
- }
-
- SALOMEDS::SObject_var so = SALOMEDS_SObject_i::New (aNewSO, _orb);
- return so._retn();
-}
-
-
-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;
-}
-
-PortableServer::POA_ptr SALOMEDS_StudyManager_i::GetPOA(const SALOMEDS::Study_ptr theStudy) {
- if (_mapOfPOA.find(theStudy->StudyId()) != _mapOfPOA.end()) return _mapOfPOA[theStudy->StudyId()];
- return PortableServer::POA::_nil();
-}
-
-CORBA::Long SALOMEDS_StudyManager_i::getPID()
-{
-#ifdef WIN32
- return (CORBA::Long)_getpid();
-#else
- return (CORBA::Long)getpid();
-#endif
-}
-
-void SALOMEDS_StudyManager_i::ShutdownWithExit()
-{
- exit( EXIT_SUCCESS );
-}
-
-//===========================================================================
-// PRIVATE FUNCTIONS
-//===========================================================================
-CORBA::LongLong SALOMEDS_StudyManager_i::GetLocalImpl(const char* theHostname, CORBA::Long thePID, CORBA::Boolean& isLocal)
-{
-#ifdef WIN32
- long pid = (long)_getpid();
-#else
- long pid = (long)getpid();
-#endif
- isLocal = (strcmp(theHostname, Kernel_Utils::GetHostname().c_str()) == 0 && pid == thePID)?1:0;
- return reinterpret_cast<CORBA::LongLong>(_impl);
-}
-
-//===========================================================================
-namespace SALOMEDS
-{
- PortableServer::ServantBase_var
- GetServant(CORBA::Object_ptr theObject, PortableServer::POA_ptr thePOA)
- {
- if(CORBA::is_nil(theObject))
- return NULL;
- try{
- return thePOA->reference_to_servant(theObject);
- }catch(...){
- return NULL;
- }
- }
-
-}
-
-//===========================================================================
+++ /dev/null
-// 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.hxx
-// Author : Sergey RUIN
-// Module : SALOME
-//
-#ifndef __SALOMEDS_STUDYMANAGER_I_H__
-#define __SALOMEDS_STUDYMANAGER_I_H__
-
-// std C++ headers
-#include <iostream>
-
-#ifndef WIN32
-#include <unistd.h>
-#endif
-
-// IDL headers
-#include <SALOMEconfig.h>
-#include CORBA_SERVER_HEADER(SALOMEDS)
-
-// Naming Service header
-#include "SALOME_NamingService.hxx"
-
-#include <stdlib.h>
-
-#include "SALOMEDS_Driver_i.hxx"
-#include "SALOMEDSImpl_StudyManager.hxx"
-
-namespace SALOMEDS{
-
- // To convert CORBA::Object to PortableServer::ServantBase
- PortableServer::ServantBase_var GetServant(CORBA::Object_ptr, PortableServer::POA_ptr);
-
-}
-
-class Standard_EXPORT SALOMEDS_StudyManager_i: public POA_SALOMEDS::StudyManager
-{
-private:
-
- CORBA::ORB_var _orb;
- PortableServer::POA_var _poa;
- SALOMEDSImpl_StudyManager* _impl;
- SALOME_NamingService* _name_service;
- SALOMEDS_DriverFactory_i* _factory;
-
-public:
-
- //! standard constructor
- SALOMEDS_StudyManager_i(CORBA::ORB_ptr orb, PortableServer::POA_ptr thePOA);
-
- //! standard destructor
- virtual ~SALOMEDS_StudyManager_i();
-
- //! method to Register study Manager in the naming service
- /*!
- \param char* arguments, the context to register the study manager in the NS
- */
- void register_name(const char * name);
-
- //! method to Create a New Study of name study_name
- /*!
- \param char* arguments, the new study name
- \return Study_ptr arguments
- */
- virtual SALOMEDS::Study_ptr NewStudy(const char* study_name) throw (SALOME::SALOME_Exception);
-
- //! method to Open a Study from it's persistent reference
- /*!
- \param char* arguments, the study URL
- \return Study_ptr arguments
- */
- virtual SALOMEDS::Study_ptr Open(const char* aStudyUrl) throw (SALOME::SALOME_Exception);
-
-
- //! method to close a Study
- /*!
- \param Study_ptr arguments
- */
- virtual void Close( SALOMEDS::Study_ptr aStudy);
-
- //! method to save a Study
- /*!
- \param Study_ptr arguments
- */
- virtual CORBA::Boolean Save( SALOMEDS::Study_ptr aStudy, CORBA::Boolean theMultiFile);
-
- virtual CORBA::Boolean SaveASCII( SALOMEDS::Study_ptr aStudy, CORBA::Boolean theMultiFile);
-
- //! method to save a Study to the persistent reference aUrl
- /*!
- \param char* arguments, the new URL of the study
- \param Study_ptr arguments
- */
- virtual CORBA::Boolean SaveAs(const char* aUrl, SALOMEDS::Study_ptr aStudy, CORBA::Boolean theMultiFile);
- virtual CORBA::Boolean SaveAsASCII(const char* aUrl, SALOMEDS::Study_ptr aStudy, CORBA::Boolean theMultiFile);
-
- //! method to Get name list of open studies in the session
- /*!
- \return ListOfOpenStudies* arguments
- */
- virtual SALOMEDS::ListOfOpenStudies* GetOpenStudies();
-
- //! method to get a Study from it's name
- /*!
- \param char* arguments, the study name
- \return Study_ptr arguments
- */
- virtual SALOMEDS::Study_ptr GetStudyByName(const char* aStudyName) ;
-
- //! method to get a Study from it's ID
- /*!
- \param char* arguments, the study ID
- \return Study_ptr arguments
- */
- virtual SALOMEDS::Study_ptr GetStudyByID(CORBA::Short aStudyID) ;
-
- virtual CORBA::Boolean CanCopy(SALOMEDS::SObject_ptr theObject);
- virtual CORBA::Boolean Copy(SALOMEDS::SObject_ptr theObject);
- virtual CORBA::Boolean CanPaste(SALOMEDS::SObject_ptr theObject);
- virtual SALOMEDS::SObject_ptr Paste(SALOMEDS::SObject_ptr theObject) throw(SALOMEDS::StudyBuilder::LockProtection);
-
- virtual char* ConvertObjectToIOR(CORBA::Object_ptr theObject) {return _orb->object_to_string(theObject); }
- virtual CORBA::Object_ptr ConvertIORToObject(const char* theIOR) { return _orb->string_to_object(theIOR); };
-
- void ping(){};
- CORBA::Long getPID();
- void ShutdownWithExit();
-
- virtual CORBA::LongLong GetLocalImpl(const char* theHostname, CORBA::Long thePID, CORBA::Boolean& isLocal);
-
- static PortableServer::POA_ptr GetPOA(const SALOMEDS::Study_ptr theStudy);
-
- void Shutdown() { if(!CORBA::is_nil(_orb)) _orb->shutdown(0); }
-};
-
-#endif
#include "utilities.h"
#include <sstream>
#include "SALOMEDS_Study_i.hxx"
-#include "SALOMEDS_StudyManager_i.hxx"
#include "SALOMEDS_UseCaseIterator_i.hxx"
#include "SALOMEDS_GenericAttribute_i.hxx"
#include "SALOMEDS_AttributeStudyProperties_i.hxx"
#include "DF_Label.hxx"
#include "DF_Attribute.hxx"
+#include "Utils_ExceptHandlers.hxx"
+
#include "Basics_Utils.hxx"
#include "SALOME_KernelServices.hxx"
#include <unistd.h>
#endif
+UNEXPECT_CATCH(SalomeException,SALOME::SALOME_Exception);
+UNEXPECT_CATCH(LockProtection, SALOMEDS::StudyBuilder::LockProtection);
+
+static SALOMEDS_Driver_i* GetDriver(const SALOMEDSImpl_SObject& theObject, CORBA::ORB_ptr orb);
+
namespace SALOMEDS
{
class Notifier: public SALOMEDSImpl_AbstractCallback
{
for (ObsListIter it (myObservers.begin()); it != myObservers.end(); ++it)
{
- if ( it->first->_is_equivalent(theObs) ) {
- myObservers.erase( it );
- break;
- }
+ if ( it->first->_is_equivalent(theObs) ) {
+ myObservers.erase( it );
+ break;
+ }
}
}
} // namespace SALOMEDS
-std::map<SALOMEDSImpl_Study* , SALOMEDS_Study_i*> SALOMEDS_Study_i::_mapOfStudies;
-
//============================================================================
/*! Function : SALOMEDS_Study_i
* Purpose : SALOMEDS_Study_i constructor
*/
//============================================================================
-SALOMEDS_Study_i::SALOMEDS_Study_i(SALOMEDSImpl_Study* theImpl,
- CORBA::ORB_ptr orb)
+SALOMEDS_Study_i::SALOMEDS_Study_i(CORBA::ORB_ptr orb)
+{
+ _orb = CORBA::ORB::_duplicate(orb);
+ _impl = new SALOMEDSImpl_Study();
+ _factory = new SALOMEDS_DriverFactory_i(_orb);
+ _closed = true;
+
+ Init();
+}
+
+//============================================================================
+/*! Function : ~SALOMEDS_Study_i
+ * Purpose : SALOMEDS_Study_i destructor
+ */
+//============================================================================
+SALOMEDS_Study_i::~SALOMEDS_Study_i()
+{
+ Clear();
+ delete _factory;
+ delete _impl;
+}
+
+//============================================================================
+/*! Function : Init
+ * Purpose : Initialize study components
+ */
+//============================================================================
+void SALOMEDS_Study_i::Init()
{
- _orb = CORBA::ORB::_duplicate(orb);
- _impl = theImpl;
+ if (!_closed)
+ throw SALOMEDS::Study::StudyInvalidReference();
+
+ SALOMEDS::Locker lock;
+
+ if ( !_impl->GetDocument() )
+ _impl->Init();
+
_builder = new SALOMEDS_StudyBuilder_i(_impl->NewBuilder(), _orb);
_notifier = new SALOMEDS::Notifier(_orb);
_genObjRegister = new SALOMEDS::GenObjRegister(_orb);
_closed = false;
- theImpl->setNotifier(_notifier);
- theImpl->setGenObjRegister( _genObjRegister );
+ _impl->setNotifier(_notifier);
+ _impl->setGenObjRegister( _genObjRegister );
+
+ // update desktop title with new study name
+ NameChanged();
// Notify GUI that study was created
SALOME_NamingService *aNamingService = KERNEL::getNamingService();
SALOME::Session_var aSession = SALOME::Session::_narrow(obj);
if ( !CORBA::is_nil(aSession) ) {
std::stringstream ss;
- ss << "studyCreated:" << theImpl->StudyId();
+ ss << "studyCreated";
std::string str = ss.str();
SALOMEDS::unlock();
aSession->emitMessageOneWay(str.c_str());
SALOMEDS::lock();
}
}
-
+
//============================================================================
-/*! Function : ~SALOMEDS_Study_i
- * Purpose : SALOMEDS_Study_i destructor
+/*! Function : Clear
+ * Purpose : Clear study components
*/
//============================================================================
-SALOMEDS_Study_i::~SALOMEDS_Study_i()
+void SALOMEDS_Study_i::Clear()
{
+ if (_closed)
+ return;
+
+ SALOMEDS::Locker lock;
+
//delete the builder servant
PortableServer::POA_var poa=_builder->_default_POA();
PortableServer::ObjectId_var anObjectId = poa->servant_to_id(_builder);
poa->deactivate_object(anObjectId.in());
_builder->_remove_ref();
-
+
+ RemovePostponed(-1);
+
+ if (_impl->GetDocument()) {
+ SALOMEDS::SComponentIterator_var itcomponent = NewComponentIterator();
+ for (; itcomponent->More(); itcomponent->Next()) {
+ SALOMEDS::SComponent_var sco = itcomponent->Value();
+ CORBA::String_var compodatatype=sco->ComponentDataType();
+ MESSAGE ( "Look for an engine for data type :"<< compodatatype);
+ // if there is an associated Engine call its method for closing
+ CORBA::String_var IOREngine;
+ if (sco->ComponentIOR(IOREngine)) {
+ // we have found the associated engine to write the data
+ MESSAGE ( "We have found an engine for data type :"<< compodatatype);
+ //_narrow can throw a corba exception
+ try {
+ CORBA::Object_var obj = _orb->string_to_object(IOREngine);
+ if (!CORBA::is_nil(obj)) {
+ SALOMEDS::Driver_var anEngine = SALOMEDS::Driver::_narrow(obj) ;
+ if (!anEngine->_is_nil()) {
+ SALOMEDS::unlock();
+ anEngine->Close(sco);
+ SALOMEDS::lock();
+ }
+ }
+ }
+ catch (CORBA::Exception&) {
+ }
+ }
+ sco->UnRegister();
+ }
+
+ //Does not need any more this iterator
+ itcomponent->UnRegister();
+ }
+
+ // Notify GUI that study is cleared
+ SALOME_NamingService *aNamingService = KERNEL::getNamingService();
+ CORBA::Object_ptr obj = aNamingService->Resolve("/Kernel/Session");
+ SALOME::Session_var aSession = SALOME::Session::_narrow(obj);
+ if ( !CORBA::is_nil(aSession) ) {
+ std::stringstream ss;
+ ss << "studyCleared";
+ std::string str = ss.str();
+ SALOMEDS::unlock();
+ aSession->emitMessageOneWay(str.c_str());
+ SALOMEDS::lock();
+ }
+
+ _impl->Clear();
_impl->setNotifier(0);
delete _notifier;
delete _genObjRegister;
- //delete implementation
- delete _impl;
- _mapOfStudies.erase(_impl);
-}
+ _notifier = NULL;
+
+ _closed = true;
+}
//============================================================================
-/*! Function : GetPersistentReference
- * Purpose : Get persistent reference of study (idem URL())
+/*! Function : Open
+ * Purpose : Open a Study from it's persistent reference
*/
//============================================================================
-char* SALOMEDS_Study_i::GetPersistentReference()
+bool SALOMEDS_Study_i::Open(const wchar_t* aWUrl)
+ throw(SALOME::SALOME_Exception)
{
- SALOMEDS::Locker lock;
+ if (!_closed)
+ Clear();
+ Init();
+ SALOMEDS::Locker lock;
+
+ Unexpect aCatch(SalomeException);
+ MESSAGE("Begin of SALOMEDS_Study_i::Open");
+
+ std::string aUrl = Kernel_Utils::encode_s(aWUrl);
+ bool res = _impl->Open(std::string(aUrl));
+
+ // update desktop title with new study name
+ NameChanged();
+
+ if ( !res )
+ THROW_SALOME_CORBA_EXCEPTION("Impossible to Open study from file", SALOME::BAD_PARAM)
+ return res;
+}
+
+//============================================================================
+/*! Function : Save
+ * Purpose : Save a Study to it's persistent reference
+ */
+//============================================================================
+CORBA::Boolean SALOMEDS_Study_i::Save(CORBA::Boolean theMultiFile, CORBA::Boolean theASCII)
+{
+ SALOMEDS::Locker lock;
if (_closed)
- throw SALOMEDS::Study::StudyInvalidReference();
- return CORBA::string_dup(_impl->GetPersistentReference().c_str());
+ throw SALOMEDS::Study::StudyInvalidReference();
+ return _impl->Save(_factory, theMultiFile, theASCII);
+}
+
+//=============================================================================
+/*! Function : SaveAs
+ * Purpose : Save a study to the persistent reference aUrl
+ */
+//============================================================================
+CORBA::Boolean SALOMEDS_Study_i::SaveAs(const wchar_t* aWUrl, CORBA::Boolean theMultiFile, CORBA::Boolean theASCII)
+{
+ SALOMEDS::Locker lock;
+ if (_closed)
+ throw SALOMEDS::Study::StudyInvalidReference();
+
+ std::string aUrl = Kernel_Utils::encode_s(aWUrl);
+ return _impl->SaveAs(std::string(aUrl), _factory, theMultiFile, theASCII);
+}
+
+//============================================================================
+/*! Function : CanCopy
+ * Purpose :
+ */
+//============================================================================
+CORBA::Boolean SALOMEDS_Study_i::CanCopy(SALOMEDS::SObject_ptr theObject)
+{
+ SALOMEDS::Locker lock;
+ if (_closed)
+ throw SALOMEDS::Study::StudyInvalidReference();
+
+ CORBA::String_var anID = theObject->GetID();
+ SALOMEDSImpl_SObject anObject = _impl->GetSObject(anID.in());
+
+ SALOMEDS_Driver_i* aDriver = GetDriver(anObject, _orb);
+ bool ret = _impl->CanCopy(anObject, aDriver);
+ delete aDriver;
+ return ret;
+}
+
+//============================================================================
+/*! Function : Copy
+ * Purpose :
+ */
+//============================================================================
+CORBA::Boolean SALOMEDS_Study_i::Copy(SALOMEDS::SObject_ptr theObject)
+{
+ SALOMEDS::Locker lock;
+ if (_closed)
+ throw SALOMEDS::Study::StudyInvalidReference();
+
+ CORBA::String_var anID = theObject->GetID();
+ SALOMEDSImpl_SObject anObject = _impl->GetSObject(anID.in());
+
+ SALOMEDS_Driver_i* aDriver = GetDriver(anObject, _orb);
+ bool ret = _impl->Copy(anObject, aDriver);
+ delete aDriver;
+ return ret;
+}
+
+//============================================================================
+/*! Function : CanPaste
+ * Purpose :
+ */
+//============================================================================
+CORBA::Boolean SALOMEDS_Study_i::CanPaste(SALOMEDS::SObject_ptr theObject)
+{
+ SALOMEDS::Locker lock;
+ if (_closed)
+ throw SALOMEDS::Study::StudyInvalidReference();
+
+ CORBA::String_var anID = theObject->GetID();
+ SALOMEDSImpl_SObject anObject = _impl->GetSObject(anID.in());
+
+ SALOMEDS_Driver_i* aDriver = GetDriver(anObject, _orb);
+ bool ret = _impl->CanPaste(anObject, aDriver);
+ delete aDriver;
+ return ret;
+}
+
+//============================================================================
+/*! Function : Paste
+ * Purpose :
+ */
+//============================================================================
+SALOMEDS::SObject_ptr SALOMEDS_Study_i::Paste(SALOMEDS::SObject_ptr theObject)
+ throw(SALOMEDS::StudyBuilder::LockProtection)
+{
+ SALOMEDS::Locker lock;
+
+ Unexpect aCatch(LockProtection);
+
+ CORBA::String_var anID = theObject->GetID();
+ SALOMEDSImpl_SObject anObject = _impl->GetSObject(anID.in());
+ SALOMEDSImpl_SObject aNewSO;
+
+ try {
+ SALOMEDS_Driver_i* aDriver = GetDriver(anObject, _orb);
+ aNewSO = _impl->Paste(anObject, aDriver);
+ delete aDriver;
+ }
+ catch (...) {
+ throw SALOMEDS::StudyBuilder::LockProtection();
+ }
+
+ SALOMEDS::SObject_var so = SALOMEDS_SObject_i::New (aNewSO, _orb);
+ return so._retn();
}
+
+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;
+}
+
//============================================================================
-/*! Function : GetTransientReference
- * Purpose : Get IOR of the Study (registred in OCAF document in doc->Root)
+/*! Function : GetPersistentReference
+ * Purpose : Get persistent reference of study (idem URL())
*/
//============================================================================
-char* SALOMEDS_Study_i::GetTransientReference()
+char* SALOMEDS_Study_i::GetPersistentReference()
{
SALOMEDS::Locker lock;
if (_closed)
throw SALOMEDS::Study::StudyInvalidReference();
- return CORBA::string_dup(_impl->GetTransientReference().c_str());
+ return CORBA::string_dup(_impl->GetPersistentReference().c_str());
}
//============================================================================
return CORBA::string_dup(aPath.c_str());
}
-
-//============================================================================
-/*! Function : SetContext
- * Purpose : Sets the current context
- */
-//============================================================================
-void SALOMEDS_Study_i::SetContext(const char* thePath)
-{
- SALOMEDS::Locker lock;
-
- if (_closed)
- throw SALOMEDS::Study::StudyInvalidReference();
-
- _impl->SetContext(std::string((char*)thePath));
- if (_impl->IsError() && _impl->GetErrorCode() == "InvalidContext")
- throw SALOMEDS::Study::StudyInvalidContext();
-}
-
-//============================================================================
-/*! Function : GetContext
- * Purpose : Gets the current context
- */
-//============================================================================
-char* SALOMEDS_Study_i::GetContext()
-{
- SALOMEDS::Locker lock;
-
- if (_closed)
- throw SALOMEDS::Study::StudyInvalidReference();
-
- if (!_impl->HasCurrentContext()) throw SALOMEDS::Study::StudyInvalidContext();
-
- return CORBA::string_dup(_impl->GetContext().c_str());
-}
-
-//============================================================================
-/*! Function : GetObjectNames
- * Purpose : method to get all object names in the given context (or in the current context, if 'theContext' is empty)
- */
-//============================================================================
-SALOMEDS::ListOfStrings* SALOMEDS_Study_i::GetObjectNames(const char* theContext)
-{
- SALOMEDS::Locker lock;
-
- if (_closed)
- throw SALOMEDS::Study::StudyInvalidReference();
-
- SALOMEDS::ListOfStrings_var aResult = new SALOMEDS::ListOfStrings;
-
- if (strlen(theContext) == 0 && !_impl->HasCurrentContext())
- throw SALOMEDS::Study::StudyInvalidContext();
-
- std::vector<std::string> aSeq = _impl->GetObjectNames(std::string((char*)theContext));
- if (_impl->GetErrorCode() == "InvalidContext")
- throw SALOMEDS::Study::StudyInvalidContext();
-
- int aLength = aSeq.size();
- aResult->length(aLength);
- for (int anIndex = 0; anIndex < aLength; anIndex++) {
- aResult[anIndex] = CORBA::string_dup(aSeq[anIndex].c_str());
- }
-
- return aResult._retn();
-}
-
-//============================================================================
-/*! Function : GetDirectoryNames
- * Purpose : method to get all directory names in the given context (or in the current context, if 'theContext' is empty)
- */
-//============================================================================
-SALOMEDS::ListOfStrings* SALOMEDS_Study_i::GetDirectoryNames(const char* theContext)
-{
- SALOMEDS::Locker lock;
-
- if (_closed)
- throw SALOMEDS::Study::StudyInvalidReference();
-
- SALOMEDS::ListOfStrings_var aResult = new SALOMEDS::ListOfStrings;
-
- if (strlen(theContext) == 0 && !_impl->HasCurrentContext())
- throw SALOMEDS::Study::StudyInvalidContext();
-
- std::vector<std::string> aSeq = _impl->GetDirectoryNames(std::string((char*)theContext));
- if (_impl->GetErrorCode() == "InvalidContext")
- throw SALOMEDS::Study::StudyInvalidContext();
-
- int aLength = aSeq.size();
- aResult->length(aLength);
- for (int anIndex = 0; anIndex < aLength; anIndex++) {
- aResult[anIndex] = CORBA::string_dup(aSeq[anIndex].c_str());
- }
-
- return aResult._retn();
-}
-
-//============================================================================
-/*! Function : GetFileNames
- * Purpose : method to get all file names in the given context (or in the current context, if 'theContext' is empty)
- */
-//============================================================================
-SALOMEDS::ListOfStrings* SALOMEDS_Study_i::GetFileNames(const char* theContext)
-{
- SALOMEDS::Locker lock;
-
- if (_closed)
- throw SALOMEDS::Study::StudyInvalidReference();
-
- SALOMEDS::ListOfStrings_var aResult = new SALOMEDS::ListOfStrings;
-
- if (strlen(theContext) == 0 && !_impl->HasCurrentContext())
- throw SALOMEDS::Study::StudyInvalidContext();
-
- std::vector<std::string> aSeq = _impl->GetFileNames(std::string((char*)theContext));
- if (_impl->GetErrorCode() == "InvalidContext")
- throw SALOMEDS::Study::StudyInvalidContext();
-
- int aLength = aSeq.size();
- aResult->length(aLength);
- for (int anIndex = 0; anIndex < aLength; anIndex++) {
- aResult[anIndex] = CORBA::string_dup(aSeq[anIndex].c_str());
- }
-
- return aResult._retn();
-}
-
-//============================================================================
-/*! Function : GetComponentNames
- * Purpose : method to get all components names
- * SRN: Note, theContext can be any, it doesn't matter
- */
-//============================================================================
-SALOMEDS::ListOfStrings* SALOMEDS_Study_i::GetComponentNames(const char* theContext)
-{
- SALOMEDS::Locker lock;
-
- if (_closed)
- throw SALOMEDS::Study::StudyInvalidReference();
-
- SALOMEDS::ListOfStrings_var aResult = new SALOMEDS::ListOfStrings;
-
- std::vector<std::string> aSeq = _impl->GetComponentNames(std::string((char*)theContext));
-
- int aLength = aSeq.size();
- aResult->length(aLength);
- for(int anIndex = 0; anIndex < aLength; anIndex++) {
- aResult[anIndex] = CORBA::string_dup(aSeq[anIndex].c_str());
- }
-
- return aResult._retn();
-}
-
//============================================================================
/*! Function : NewChildIterator
* Purpose : Create a ChildIterator from an SObject
* Purpose : get study name
*/
//============================================================================
-char* SALOMEDS_Study_i::Name()
+wchar_t* SALOMEDS_Study_i::Name()
{
SALOMEDS::Locker lock;
// Name is specified as IDL attribute: user exception cannot be raised
- return CORBA::string_dup(_impl->Name().c_str());
+ return CORBA::wstring_dup(Kernel_Utils::decode_s(_impl->Name()));
}
//============================================================================
* Purpose : set study name
*/
//============================================================================
-void SALOMEDS_Study_i::Name(const char* name)
+void SALOMEDS_Study_i::Name(const wchar_t* wname)
{
- SALOMEDS::Locker lock;
+ SALOMEDS::Locker lock;
// Name is specified as IDL attribute: user exception cannot be raised
- _impl->Name(std::string(name));
+ _impl->Name(Kernel_Utils::encode_s(wname));
}
//============================================================================
* Purpose : get URL of the study (persistent reference of the study)
*/
//============================================================================
-char* SALOMEDS_Study_i::URL()
+wchar_t* SALOMEDS_Study_i::URL()
{
- SALOMEDS::Locker lock;
+ SALOMEDS::Locker lock;
// URL is specified as IDL attribute: user exception cannot be raised
- return CORBA::string_dup(_impl->URL().c_str());
+ return CORBA::wstring_dup(Kernel_Utils::decode_s(_impl->URL()));
}
//============================================================================
* Purpose : set URL of the study (persistent reference of the study)
*/
//============================================================================
-void SALOMEDS_Study_i::URL(const char* url)
+void SALOMEDS_Study_i::URL(const wchar_t* wurl)
{
SALOMEDS::Locker lock;
// URL is specified as IDL attribute: user exception cannot be raised
- _impl->URL(std::string((char*)url));
-}
+ _impl->URL(Kernel_Utils::encode_s(wurl));
-CORBA::Short SALOMEDS_Study_i::StudyId()
-{
- SALOMEDS::Locker lock;
- // StudyId is specified as IDL attribute: user exception cannot be raised
- return _impl->StudyId();
-}
-
-void SALOMEDS_Study_i::StudyId(CORBA::Short id)
-{
- SALOMEDS::Locker lock;
- // StudyId is specified as IDL attribute: user exception cannot be raised
- _impl->StudyId(id);
+ // update desktop title with new study name
+ NameChanged();
}
void SALOMEDS_Study_i::UpdateIORLabelMap(const char* anIOR, const char* anEntry)
_impl->UpdateIORLabelMap(std::string((char*)anIOR), std::string((char*)anEntry));
}
-SALOMEDS::Study_ptr SALOMEDS_Study_i::GetStudy(const DF_Label& theLabel, CORBA::ORB_ptr orb)
-{
- SALOMEDS::Locker lock;
-
- SALOMEDSImpl_AttributeIOR* Att = NULL;
- if ((Att=(SALOMEDSImpl_AttributeIOR*)theLabel.Root().FindAttribute(SALOMEDSImpl_AttributeIOR::GetID()))){
- char* IOR = CORBA::string_dup(Att->Value().c_str());
- CORBA::Object_var obj = orb->string_to_object(IOR);
- SALOMEDS::Study_ptr aStudy = SALOMEDS::Study::_narrow(obj) ;
- ASSERT(!CORBA::is_nil(aStudy));
- return SALOMEDS::Study::_duplicate(aStudy);
- } else {
- MESSAGE("GetStudy: Problem to get study");
- }
- return SALOMEDS::Study::_nil();
-}
-
-SALOMEDS_Study_i* SALOMEDS_Study_i::GetStudyServant(SALOMEDSImpl_Study* aStudyImpl, CORBA::ORB_ptr orb)
-{
- if (_mapOfStudies.find(aStudyImpl) != _mapOfStudies.end())
- return _mapOfStudies[aStudyImpl];
- else
- {
- SALOMEDS_Study_i *Study_servant = new SALOMEDS_Study_i(aStudyImpl, orb);
- _mapOfStudies[aStudyImpl]=Study_servant;
- return Study_servant;
- }
-}
-
void SALOMEDS_Study_i::IORUpdated(SALOMEDSImpl_AttributeIOR* theAttribute)
{
SALOMEDS::Locker lock;
return uc._retn();
}
-
-//============================================================================
-/*! Function : Close
- * Purpose :
- */
-//============================================================================
-void SALOMEDS_Study_i::Close()
-{
- SALOMEDS::Locker lock;
-
- if (_closed)
- throw SALOMEDS::Study::StudyInvalidReference();
-
- RemovePostponed(-1);
-
- SALOMEDS::SComponentIterator_var itcomponent = NewComponentIterator();
- for (; itcomponent->More(); itcomponent->Next()) {
- SALOMEDS::SComponent_var sco = itcomponent->Value();
- CORBA::String_var compodatatype=sco->ComponentDataType();
- MESSAGE ( "Look for an engine for data type :"<< compodatatype);
- // if there is an associated Engine call its method for closing
- CORBA::String_var IOREngine;
- if (sco->ComponentIOR(IOREngine)) {
- // we have found the associated engine to write the data
- MESSAGE ( "We have found an engine for data type :"<< compodatatype);
- //_narrow can throw a corba exception
- try {
- CORBA::Object_var obj = _orb->string_to_object(IOREngine);
- if (!CORBA::is_nil(obj)) {
- SALOMEDS::Driver_var anEngine = SALOMEDS::Driver::_narrow(obj) ;
- if (!anEngine->_is_nil()) {
- SALOMEDS::unlock();
- anEngine->Close(sco);
- SALOMEDS::lock();
- }
- }
- }
- catch (CORBA::Exception&) {
- }
- }
- sco->UnRegister();
- }
-
- //Does not need any more this iterator
- itcomponent->UnRegister();
-
- // Notify GUI that study is closed
- SALOME_NamingService *aNamingService = KERNEL::getNamingService();
- CORBA::Object_ptr obj = aNamingService->Resolve("/Kernel/Session");
- SALOME::Session_var aSession = SALOME::Session::_narrow(obj);
- if ( !CORBA::is_nil(aSession) ) {
- std::stringstream ss;
- ss << "studyClosed:" << _impl->StudyId();
- std::string str = ss.str();
- SALOMEDS::unlock();
- aSession->emitMessageOneWay(str.c_str());
- SALOMEDS::lock();
- }
-
- _impl->Close();
- _closed = true;
-}
-
//============================================================================
/*! Function : AddPostponed
* Purpose :
}
}
+
+CORBA::Long SALOMEDS_Study_i::getPID()
+{
+#ifdef WIN32
+ return (CORBA::Long)_getpid();
+#else
+ return (CORBA::Long)getpid();
+#endif
+}
+
+void SALOMEDS_Study_i::ShutdownWithExit()
+{
+ exit( EXIT_SUCCESS );
+}
+
+void SALOMEDS_Study_i::Shutdown()
+{
+ if(!CORBA::is_nil(_orb))
+ _orb->shutdown(0);
+}
+
//============================================================================
/*! Function : attach
* Purpose : This function attach an observer to the study
isLocal = (strcmp(theHostname, Kernel_Utils::GetHostname().c_str()) == 0 && pid == thePID)?1:0;
return reinterpret_cast<CORBA::LongLong>(_impl);
}
+
+void SALOMEDS_Study_i::NameChanged()
+{
+ // Notify GUI that the name of study was changed
+ SALOME_NamingService *aNamingService = KERNEL::getNamingService();
+ CORBA::Object_var obj = aNamingService->Resolve("/Kernel/Session");
+ SALOME::Session_var aSession = SALOME::Session::_narrow(obj);
+ if ( !CORBA::is_nil(aSession) ) {
+ std::stringstream ss;
+ ss << "studyNameChanged";
+ std::string str = ss.str();
+ SALOMEDS::unlock();
+ aSession->emitMessageOneWay(str.c_str());
+ SALOMEDS::lock();
+ }
+}
#include "SALOMEDS_StudyBuilder_i.hxx"
#include "SALOMEDS_SObject_i.hxx"
#include "SALOMEDS_UseCaseBuilder_i.hxx"
+#include "SALOMEDS_Driver_i.hxx"
#include "SALOMEDSImpl_Study.hxx"
#include "SALOMEDSImpl_AttributeIOR.hxx"
class Standard_EXPORT SALOMEDS_Study_i: public POA_SALOMEDS::Study
{
private:
+
+ void NameChanged();
CORBA::ORB_var _orb;
SALOMEDSImpl_Study* _impl;
SALOMEDS_StudyBuilder_i* _builder;
- static std::map<SALOMEDSImpl_Study*, SALOMEDS_Study_i*> _mapOfStudies;
SALOMEDSImpl_AbstractCallback* _notifier;
SALOMEDSImpl_AbstractCallback* _genObjRegister;
+ SALOMEDS_DriverFactory_i* _factory;
bool _closed;
public:
//! standard constructor
- SALOMEDS_Study_i(SALOMEDSImpl_Study*, CORBA::ORB_ptr);
+ SALOMEDS_Study_i(CORBA::ORB_ptr);
//! standard destructor
- virtual ~SALOMEDS_Study_i();
+ virtual ~SALOMEDS_Study_i();
+ virtual void Init();
+ virtual void Clear();
+
+ //! method to Open a Study
+ /*!
+ \param char* arguments, the study URL
+ \return Study_ptr arguments
+ */
+ virtual bool Open(const wchar_t* aStudyUrl) throw (SALOME::SALOME_Exception);
+
+ //! method to save a Study
+ virtual CORBA::Boolean Save(CORBA::Boolean theMultiFile, CORBA::Boolean theASCII);
+
+ //! method to save a Study to the persistent reference aUrl
+ /*!
+ \param char* arguments, the new URL of the study
+ */
+ virtual CORBA::Boolean SaveAs(const wchar_t* aUrl, CORBA::Boolean theMultiFile, CORBA::Boolean theASCII);
+
+ //! method to copy the object
+ /*!
+ \param theObject object to copy
+ */
+ virtual CORBA::Boolean Copy(SALOMEDS::SObject_ptr theObject);
+ virtual CORBA::Boolean CanCopy(SALOMEDS::SObject_ptr theObject);
+ //! method to paste the object in study
+ /*!
+ \param theObject object to paste
+ */
+ virtual SALOMEDS::SObject_ptr Paste(SALOMEDS::SObject_ptr theObject) throw(SALOMEDS::StudyBuilder::LockProtection);
+ virtual CORBA::Boolean CanPaste(SALOMEDS::SObject_ptr theObject);
+
//! method to Get persistent reference of study (idem URL())
/*!
\sa URL()
*/
virtual char* GetPersistentReference();
-
- //! method to Get transient reference of study
- /*!
- \return char* arguments, the transient reference of the study
- */
- virtual char* GetTransientReference();
-
//! method to detect if a study is empty
/*!
\return bool arguments, true if study is empty
*/
virtual char* GetObjectPath(CORBA::Object_ptr theObject);
- //! method to set a context: root ('/') is UserData component
- /*!
- */
- virtual void SetContext(const char* thePath);
-
- //! method to get a context
- /*!
- */
- virtual char* GetContext();
-
- //! method to get all object names in the given context (or in the current context, if 'theContext' is empty)
- /*!
- */
- virtual SALOMEDS::ListOfStrings* GetObjectNames(const char* theContext);
-
- //! method to get all directory names in the given context (or in the current context, if 'theContext' is empty)
- /*!
- */
- virtual SALOMEDS::ListOfStrings* GetDirectoryNames(const char* theContext);
-
- //! method to get all file names in the given context (or in the current context, if 'theContext' is empty)
- /*!
- */
- virtual SALOMEDS::ListOfStrings* GetFileNames(const char* theContext);
-
- //! method to get all components names
- /*!
- */
- virtual SALOMEDS::ListOfStrings* GetComponentNames(const char* theContext);
-
//! method to Create a ChildIterator from an SObject
/*!
\param aSO SObject_ptr arguments
/*!
\return char* arguments, the study name
*/
- virtual char* Name();
+ virtual wchar_t* Name();
//! method to set study name
/*!
\param name char* arguments, the study name
*/
- virtual void Name(const char* name);
+ virtual void Name(const wchar_t* name);
//! method to get if study has been saved
/*!
/*!
\return char* arguments, the study URL
*/
- virtual char* URL();
+ virtual wchar_t* URL();
//! method to set URL of the study
/*!
\param url char* arguments, the study URL
*/
- virtual void URL(const char* url);
-
- virtual CORBA::Short StudyId();
- virtual void StudyId(CORBA::Short id);
-
- static SALOMEDS::Study_ptr GetStudy(const DF_Label& theLabel, CORBA::ORB_ptr orb);
- static SALOMEDS_Study_i* GetStudyServant(SALOMEDSImpl_Study*, CORBA::ORB_ptr orb);
+ virtual void URL(const wchar_t* url);
static void IORUpdated(SALOMEDSImpl_AttributeIOR* theAttribute);
virtual SALOMEDS::UseCaseBuilder_ptr GetUseCaseBuilder();
- virtual void Close();
-
void EnableUseCaseAutoFilling(CORBA::Boolean isEnabled);
// postponed destroying of CORBA object functionality
virtual CORBA::LongLong GetLocalImpl(const char* theHostname, CORBA::Long thePID, CORBA::Boolean& isLocal);
+ void ping(){};
+ CORBA::Long getPID();
+ void ShutdownWithExit();
+
+ void Shutdown();
+
virtual void attach(SALOMEDS::Observer_ptr theObs, CORBA::Boolean modify);
virtual void detach(SALOMEDS::Observer_ptr theObs);
};
def CanPublishInStudy(self, theIOR):
return 1
- def PublishInStudy(self, theStudy, theSObject, theObject, theName):
+ def PublishInStudy(self, theSObject, theObject, theName):
return None
def CanCopy(self, theObject):
${CMAKE_CURRENT_SOURCE_DIR}/../../DF
${CMAKE_CURRENT_SOURCE_DIR}/../../SALOMEDSImpl
${CMAKE_CURRENT_SOURCE_DIR}/../../SALOMEDSImpl/Test
+ ${CMAKE_CURRENT_SOURCE_DIR}/../../GenericObj
${PROJECT_BINARY_DIR}/idl
)
SalomeDSImpl
SalomeDSClient
SalomeDS
+ SalomeGenericObj
SalomeIDLKernel
)
#include "SALOMEDSTest.hxx"
-
-#include "SALOMEDS_StudyManager_i.hxx"
#include "utilities.h"
#include "Utils_SINGLETON.hxx"
#include "Utils_ORB_INIT.hxx"
#include <cstdlib>
#include "SALOMEDSClient.hxx"
-#include "SALOMEDS_StudyManager_i.hxx"
-#include "SALOMEDS_StudyManager.hxx"
+#include "SALOMEDS_Study.hxx"
#include "SALOMEDS_SObject.hxx"
ASSERT(SINGLETON_<ORB_INIT>::IsAlreadyExisting());
_orb = init(argc , argv ) ;
SALOME_NamingService NS(_orb);
- CORBA::Object_var obj = NS.Resolve( "/myStudyManager" );
- _sm = SALOMEDS::StudyManager::_narrow( obj );
+ CORBA::Object_var obj = NS.Resolve( "/Study" );
+ _study = SALOMEDS::Study::_narrow( obj );
- CPPUNIT_ASSERT( !CORBA::is_nil(_sm) );
+ CPPUNIT_ASSERT( !CORBA::is_nil(_study) );
}
// ============================================================================
void SALOMEDSTest::tearDown()
{
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
- std::vector<std::string> v = sm->GetOpenStudies();
- for(int i = 0; i<v.size(); i++) {
- _PTR(Study) study = sm->GetStudyByName(v[i]);
- if(study)
- sm->Close(study);
- }
+ _PTR(Study) study ( new SALOMEDS_Study(_study) );
+ if(study)
+ study->Clear();
}
#include "SALOMEDSTest_AttributeComment.cxx"
#include "SALOMEDSTest_SObject.cxx"
#include "SALOMEDSTest_Study.cxx"
#include "SALOMEDSTest_StudyBuilder.cxx"
-#include "SALOMEDSTest_StudyManager.cxx"
#include "SALOMEDSTest_UseCase.cxx"
ASSERT(SINGLETON_<ORB_INIT>::IsAlreadyExisting());
_orb = init(argc , argv ) ;
SALOME_NamingService NS(_orb);
- CORBA::Object_var obj = NS.Resolve( "/myStudyManager_embedded" );
- _sm = SALOMEDS::StudyManager::_narrow( obj );
+ CORBA::Object_var obj = NS.Resolve( "/Study_embedded" );
+ _study = SALOMEDS::Study::_narrow( obj );
- CPPUNIT_ASSERT( !CORBA::is_nil(_sm) );
+ CPPUNIT_ASSERT( !CORBA::is_nil(_study) );
}
CPPUNIT_TEST( testSObject );
CPPUNIT_TEST( testStudy );
CPPUNIT_TEST( testStudyBuilder );
- CPPUNIT_TEST( testStudyManager );
CPPUNIT_TEST( testUseCase );
void testSObject();
void testStudy();
void testStudyBuilder();
- void testStudyManager();
void testUseCase();
protected:
-SALOMEDS::StudyManager_var _sm;
-CORBA::ORB_var _orb;
+SALOMEDS::Study_var _study;
+CORBA::ORB_var _orb;
};
CPPUNIT_TEST( testStudy );
CPPUNIT_TEST( testStudyBuilder );
CPPUNIT_TEST( testChildIterator );
- CPPUNIT_TEST( testStudyManager );
CPPUNIT_TEST( testUseCase );
CPPUNIT_TEST_SUITE_END();
* Use code of SALOMEDS_AttributeComment.cxx
*/
+//#include "Basics_Utils.hxx"
+
void SALOMEDSTest::testAttributeComment()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm(new SALOMEDS_StudyManager(_sm));
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- std::vector<std::string> ost(sm->GetOpenStudies());
- _PTR(Study) study;
- if(ost.empty())
- study = sm->NewStudy("Test");
- else
- study = sm->GetStudyByName(ost[0]);
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
_attr->SetValue("");
CPPUNIT_ASSERT(_attr->Value() == "");
-
- sm->Close(study);
+ study->Clear();
}
void SALOMEDSTest::testAttributeDrawable()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm(new SALOMEDS_StudyManager(_sm));
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
CPPUNIT_ASSERT(!_attr->IsDrawable());
- sm->Close(study);
+ study->Clear();
}
*/
void SALOMEDSTest::testAttributeExpandable()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
CPPUNIT_ASSERT(_attr->IsExpandable());
- sm->Close(study);
+ study->Clear();
}
*/
void SALOMEDSTest::testAttributeExternalFileDef()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
_attr->SetValue("");
CPPUNIT_ASSERT(_attr->Value() == "");
-
- sm->Close(study);
+ study->Clear();
}
*/
void SALOMEDSTest::testAttributeFileType()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
_attr->SetValue("");
CPPUNIT_ASSERT(_attr->Value() == "");
-
- sm->Close(study);
+ study->Clear();
}
*/
void SALOMEDSTest::testAttributeFlags()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
CPPUNIT_ASSERT(!_attr->Get(4));
- sm->Close(study);
+ study->Clear();
}
*/
void SALOMEDSTest::testAttributeGraphic()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
_attr->SetVisibility(-1, true);
CPPUNIT_ASSERT(_attr->GetVisibility(-1));
- sm->Close(study);
+ study->Clear();
}
*/
void SALOMEDSTest::testAttributeIOR()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
CPPUNIT_ASSERT(value.empty());
- std::string ior = _orb->object_to_string(_sm);
+ std::string ior = _orb->object_to_string(_study);
//Check method SetValue
_attr->SetValue(ior);
CPPUNIT_ASSERT(ior == _attr->Value());
- sm->Close(study);
+ study->Clear();
}
*/
void SALOMEDSTest::testAttributeInteger()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
//Check method Value
CPPUNIT_ASSERT(_attr->Value() == value);
- sm->Close(study);
+ study->Clear();
}
*/
void SALOMEDSTest::testAttributeLocalID()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
//Check method Value
CPPUNIT_ASSERT(_attr->Value() == value);
- sm->Close(study);
+ study->Clear();
}
*/
void SALOMEDSTest::testAttributeName()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
_attr->SetValue("");
CPPUNIT_ASSERT(_attr->Value() == "");
- sm->Close(study);
+ study->Clear();
}
*/
void SALOMEDSTest::testAttributeOpened()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
CPPUNIT_ASSERT(!_attr->IsOpened());
- sm->Close(study);
+ study->Clear();
}
*/
void SALOMEDSTest::testAttributeParameter()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
CPPUNIT_ASSERT(_attr->IsSet("StrArray", PT_STRARRAY) && _attr->GetStrArray("StrArray")[1] == "world");
*/
- sm->Close(study);
+ study->Clear();
}
*/
void SALOMEDSTest::testAttributePersistentRef()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
_attr->SetValue("");
CPPUNIT_ASSERT(_attr->Value() == "");
- sm->Close(study);
+ study->Clear();
}
*/
void SALOMEDSTest::testAttributePixMap()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
_attr->SetPixMap("");
CPPUNIT_ASSERT(_attr->GetPixMap() == "");
-
- sm->Close(study);
+ study->Clear();
}
*/
void SALOMEDSTest::testAttributePythonObject()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
_attr->SetObject("", true);
CPPUNIT_ASSERT(_attr->GetObject() == "" && _attr->IsScript());
- sm->Close(study);
+ study->Clear();
}
*/
void SALOMEDSTest::testAttributeReal()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
//Check method Value
CPPUNIT_ASSERT(_attr->Value() == value);
- sm->Close(study);
+ study->Clear();
}
*/
void SALOMEDSTest::testAttributeSelectable()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
CPPUNIT_ASSERT(_attr->IsSelectable());
- sm->Close(study);
+ study->Clear();
}
*/
void SALOMEDSTest::testAttributeSequenceOfInteger()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
}
CPPUNIT_ASSERT(isRaised);
- sm->Close(study);
+ study->Clear();
}
*/
void SALOMEDSTest::testAttributeSequenceOfReal()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
}
CPPUNIT_ASSERT(isRaised);
- sm->Close(study);
+ study->Clear();
}
*/
void SALOMEDSTest::testAttributeStudyProperties()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
_attr->GetModificationsList(vs, vi[0], vi[1], vi[2], vi[3], vi[4], true);
CPPUNIT_ASSERT(vs[0] == "srn" && vi[0][0] == 1 && vi[1][0] == 2 && vi[2][0] == 3 && vi[3][0] == 4 && vi[4][0] == 5);
- sm->Close(study);
+ study->Clear();
}
*/
void SALOMEDSTest::testAttributeTableOfInteger()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
CPPUNIT_ASSERT(data2.size() == 3 && data2[0] == 11 && data2[1] == -22 && data2[2] == -33);
- sm->Close(study);
+ study->Clear();
}
*/
void SALOMEDSTest::testAttributeTableOfReal()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
CPPUNIT_ASSERT(data2.size() == 3 && data2[0] == 11.11 && data2[1] == -22.22 && data2[2] == -33.33);
- sm->Close(study);
+ study->Clear();
}
*/
void SALOMEDSTest::testAttributeTableOfString()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
CPPUNIT_ASSERT(data2.size() == 3 && data2[0] == "11" && data2[1] == "-22" && data2[2] == "-33");
- sm->Close(study);
+ study->Clear();
}
*/
void SALOMEDSTest::testAttributeTarget()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
CPPUNIT_ASSERT(v[0]->GetID() == "0:1:3");
- sm->Close(study);
+ study->Clear();
}
*/
void SALOMEDSTest::testAttributeTextColor()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
CPPUNIT_ASSERT(color.B == color2.B);
- sm->Close(study);
+ study->Clear();
}
*/
void SALOMEDSTest::testAttributeTextHighlightColor()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
CPPUNIT_ASSERT(color.B == color2.B);
- sm->Close(study);
+ study->Clear();
}
#define SALOMEDS_ALL_TESTS
void SALOMEDSTest::testAttributeTreeNode()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
_PTR(AttributeTreeNode) _attr_guid = studyBuilder->FindOrCreateAttribute(so, "AttributeTreeNodeGUID"+value);
CPPUNIT_ASSERT(_attr_guid && _attr_guid->GetTreeID() == value);
- sm->Close(study);
+ study->Clear();
}
#undef SALOMEDS_ALL_TESTS
*/
void SALOMEDSTest::testAttributeUserID()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
_PTR(AttributeUserID) _attr2 = studyBuilder->FindOrCreateAttribute(so, "AttributeUserID"+value);
CPPUNIT_ASSERT(_attr2 && _attr2->Value() == value);
- sm->Close(study);
+ study->Clear();
}
*/
void SALOMEDSTest::testChildIterator()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
//Check that there are two SObject under so
CPPUNIT_ASSERT(count == 2);
- sm->Close(study);
+ study->Clear();
}
*/
void SALOMEDSTest::testSComponent()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
//Check method ComponentIOR
- std::string ior = _orb->object_to_string(_sm);
+ std::string ior = _orb->object_to_string(_study);
_attr->SetValue(ior);
std::string new_ior;
//Check method ComponentDataType
CPPUNIT_ASSERT(sco->ComponentDataType() == "Test");
- sm->Close(study);
+ study->Clear();
}
*/
void SALOMEDSTest::testSComponentIterator()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
CPPUNIT_ASSERT(ci->Value()->ComponentDataType() == v[i]);
}
- sm->Close(study);
+ study->Clear();
}
void SALOMEDSTest::testSObject()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("TestSObject");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
_PTR(AttributeName) _attrName = studyBuilder->FindOrCreateAttribute(so, "AttributeName");
_PTR(AttributeComment) _attrComment = studyBuilder->FindOrCreateAttribute(so, "AttributeComment");
- std::string ior = _orb->object_to_string(_sm);
+ std::string ior = _orb->object_to_string(_study);
_attrIOR->SetValue(ior);
_attrName->SetValue("SO name");
_attrComment->SetValue("SO comment");
CPPUNIT_ASSERT(so->FindSubObject(1, so2));
CPPUNIT_ASSERT(so2->GetID() == so1->GetID());
- //Check method GetStudy
- CPPUNIT_ASSERT(so->GetStudy()->StudyId() == study->StudyId());
-
//Check methods Name
so->Name("test");
CPPUNIT_ASSERT(so->Name() == "test");
CORBA::Object_var obj = dynamic_cast<SALOMEDS_SObject*>(so.get())->GetObject();
CPPUNIT_ASSERT(!CORBA::is_nil(obj));
- sm->Close(study);
+ study->Clear();
}
void SALOMEDSTest::testStudy()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("Test");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
//Check the creation of the study
CPPUNIT_ASSERT(study);
CPPUNIT_ASSERT(componentIterator);
- //Check method GetTransientReference
- CPPUNIT_ASSERT(!study->GetTransientReference().empty());
-
- //Check method StudyId
- CPPUNIT_ASSERT(study->StudyId() > 0);
-
- //Check method Name (get/set)
- CPPUNIT_ASSERT(study->Name() == "Test");
- study->Name("New name");
- CPPUNIT_ASSERT(study->Name() == "New name");
- study->Name("Test");
-
//Check method URL (get/set)
study->URL("");
CPPUNIT_ASSERT(study->URL() == "");
//Try to find component with empty type
CPPUNIT_ASSERT(!study->FindComponent(""));
- //Check method GetComponentNames
- std::vector<std::string> components = study->GetComponentNames(""); //The context doesn't matter
- CPPUNIT_ASSERT(components.size() == 1 && components[0] == "sco1");
-
//Check method FindComponentID
_PTR(SComponent) sco3 = study->FindComponentID(sco1->GetID());
CPPUNIT_ASSERT(sco3 && sco3->GetID() == sco1->GetID());
_PTR(AttributeIOR) ior_attr_so1 = studyBuilder->FindOrCreateAttribute(so1, "AttributeIOR");
CPPUNIT_ASSERT(ior_attr_so1);
- std::string ior = _orb->object_to_string(_sm);
+ std::string ior = _orb->object_to_string(_study);
ior_attr_so1->SetValue(ior);
_PTR(SObject) so2 = studyBuilder->NewObject(so1);
path = study->GetObjectPath(emptySO);
CPPUNIT_ASSERT(path.empty());
- //Check method SetContext
- study->SetContext("/sco1");
- CPPUNIT_ASSERT(study->GetContext() == "/sco1");
-
//Check method FindObjectByPath
_PTR(SObject) so6 = study->FindObjectByPath("so1");
CPPUNIT_ASSERT(so6 && so6->GetID() == so1->GetID());
_PTR(SObject) tmp = study->FindObjectByPath(""); //Must return the Context SObject
CPPUNIT_ASSERT(tmp && tmp->GetID() == sco1->GetID());
- study->SetContext("/"); //Root
-
- //Check method GetObjectNames
- std::vector<std::string> vs = study->GetObjectNames("/sco1");
- CPPUNIT_ASSERT(vs.size() == 2);
-
- //Check method GetDirectoryNames
- _PTR(AttributeLocalID) locid_attr_sco1 = studyBuilder->FindOrCreateAttribute(sco1, "AttributeLocalID");
- CPPUNIT_ASSERT(locid_attr_sco1);
- locid_attr_sco1->SetValue(16661); //DIRECTORYID
- _PTR(AttributeLocalID) locid_attr_so1 = studyBuilder->FindOrCreateAttribute(so1, "AttributeLocalID");
- CPPUNIT_ASSERT(locid_attr_so1);
- locid_attr_so1->SetValue(16661); //DIRECTORYID
- vs = study->GetDirectoryNames(""); //Empty context (the current is taken)
- CPPUNIT_ASSERT(vs.size() == 2);
-
- //Check method GetFileNames
- locid_attr_sco1->SetValue(26662); //FILELOCALID
- _PTR(AttributePersistentRef) persref_attr_sco1 = studyBuilder->FindOrCreateAttribute(sco1, "AttributePersistentRef");
- CPPUNIT_ASSERT(persref_attr_sco1);
- persref_attr_sco1->SetValue("FILE: filename1");
- locid_attr_so1->SetValue(26662); //FILELOCALID
- _PTR(AttributePersistentRef) persref_attr_so1 = studyBuilder->FindOrCreateAttribute(so1, "AttributePersistentRef");
- CPPUNIT_ASSERT(persref_attr_so1);
- persref_attr_so1->SetValue("FILE: filename2");
- vs = study->GetFileNames("");
- CPPUNIT_ASSERT(vs.size() == 2 && vs[0] == "filename1" && vs[1] == "filename2");
-
- //Check method StudyId (get/set)
- int id = study->StudyId();
- study->StudyId(-1);
- CPPUNIT_ASSERT(study->StudyId() == -1);
- study->StudyId(id);
-
//Check method FindDependances
studyBuilder->Addreference(so2, so1);
studyBuilder->Addreference(sco1, so1);
CPPUNIT_ASSERT(date == "08/09/0010 07:06");
//Check method GetModificationsDate
- vs = study->GetModificationsDate();
+ std::vector<std::string> vs = study->GetModificationsDate();
CPPUNIT_ASSERT(vs.size() == 2 && vs[0] == "03/04/0005 02:01" && vs[1] == "08/09/0010 07:06");
//Check method GetCommonParameters
system("rm -f SRN.py");
CPPUNIT_ASSERT(line.substr(0,50) == "### This file is generated automatically by SALOME");
- //Check method Close
+ //Check method Clear
bool isException = false;
try {
- sm->Close(study); //Close is called inside StudyManager::Close
+ study->Clear(); //Clear is called inside Study::Clear()
}
catch(...) {
isException = true;
void SALOMEDSTest::testStudyBuilder()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Create a new study
- _PTR(Study) study = sm->NewStudy("TestStudyBuilder");
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
CPPUNIT_ASSERT(study);
CPPUNIT_ASSERT(sco1 && sco1->ComponentDataType() == "Test");
//Check method DefineComponentInstance
- std::string ior = _orb->object_to_string(_sm);
+ std::string ior = _orb->object_to_string(_study);
studyBuilder->DefineComponentInstance(sco1, ior);
std::string newior;
sco1->ComponentIOR(newior);
studyBuilder->SetIOR(so1, ior);
CPPUNIT_ASSERT(so1->GetIOR() == ior);
- sm->Close(study);
+ study->Clear();
//Check method LoadWith
- _PTR(Study) study2 = sm->NewStudy("Study2");
+ _PTR(Study) study2(new SALOMEDS_Study(new SALOMEDSImpl_Study()));
SALOME_NamingService NS(_orb);
CORBA::Object_var obj = SALOME_LifeCycleCORBA(&NS).FindOrLoad_Component("FactoryServer", "SMESH");
ior = _orb->object_to_string(drv);
sb2->DefineComponentInstance(sco, ior);
- sm->SaveAs("srn_SALOMEDS_UnitTests.hdf", study2, false);
- sm->Close(study2);
+ study2->SaveAs("srn_SALOMEDS_UnitTests.hdf", false, false);
+ study2->Clear();
- _PTR(Study) study3 = sm->Open("srn_SALOMEDS_UnitTests.hdf");
+ _PTR(Study) study3(new SALOMEDS_Study(new SALOMEDSImpl_Study()));
+ study3->Open("srn_SALOMEDS_UnitTests.hdf");
_PTR(StudyBuilder) sb3 = study3->NewBuilder();
_PTR(SComponent) aComp = study3->FindComponent("SMESH");
CPPUNIT_ASSERT(aComp);
isRaised = true;
}
-
CPPUNIT_ASSERT(!isRaised);
ior = "";
system("rm -f srn_SALOMEDS_UnitTests.hdf");
- //Check method AddDirectory
- _PTR(AttributeName) na1 = sb3->FindOrCreateAttribute(aComp, "AttributeName");
- na1->SetValue("Component");
-
- isRaised = false;
- try {
- sb3->AddDirectory("/Component/Dir1");
- } catch(...) {
- isRaised = true;
- }
-
-
- CPPUNIT_ASSERT(!isRaised);
- _PTR(SObject) so5 = study3->FindObjectByPath("/Component/Dir1");
- CPPUNIT_ASSERT(so5);
-
- isRaised = false;
- try {
- sb3->AddDirectory("/Component/Dir1"); //Attempt to create the same directory
- } catch(...) {
- isRaised = true;
- }
- CPPUNIT_ASSERT(isRaised);
-
- isRaised = false;
- try {
- sb3->AddDirectory("/MyComponent/Dir1"); //Attempt to create the invalid directory
- } catch(...) {
- isRaised = true;
- }
- CPPUNIT_ASSERT(isRaised);
-
- sm->Close(study3);
+ study3->Clear();
}
+++ /dev/null
-// 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
-//
-
-/*!
- * Check all methods of SALOMEDS_StudyManager
- * Use code of SALOMEDS_StudyManager.cxx
- */
-void SALOMEDSTest::testStudyManager()
-{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
-
- CPPUNIT_ASSERT(sm);
-
- //Check method NewStudy
- _PTR(Study) study1 = sm->NewStudy("Study1");
- CPPUNIT_ASSERT(study1);
-
- //Check method GetStudyByName
- _PTR(Study) study3 = sm->GetStudyByName("Study1");
- CPPUNIT_ASSERT(study3->StudyId() == study1->StudyId());
- CPPUNIT_ASSERT(study3->Name() == study1->Name());
-
- //Check method GetOpenStudies
- std::vector<std::string> v = sm->GetOpenStudies();
- CPPUNIT_ASSERT(v.size() == 1);
-
- //Check method GetStudyByID for invalid ID
- CPPUNIT_ASSERT(!sm->GetStudyByID(-1));
-
- //Check methods CanPaste, CanCopy, Copy, Paste
- _PTR(StudyBuilder) sb1 = study1->NewBuilder();
- _PTR(SComponent) sco1 = sb1->NewComponent("Test");
- _PTR(SObject) so1 = sb1->NewObject(sco1);
- _PTR(AttributeName) na1 = sb1->FindOrCreateAttribute(so1, "AttributeName");
- CPPUNIT_ASSERT(na1);
- na1->SetValue("Some name");
-
- CPPUNIT_ASSERT(!sm->CanCopy(so1)); //The father component has no IOR
-
- CPPUNIT_ASSERT(sm->Copy(so1));
-
- CPPUNIT_ASSERT(!sm->CanPaste(so1)); //The father component has no IOR
-
- _PTR(SObject) so1_2 = sb1->NewObject(sco1);
- _PTR(SObject) pasted_so = sm->Paste(so1_2);
- CPPUNIT_ASSERT(pasted_so);
-
- _PTR(AttributeName) na2 = sb1->FindOrCreateAttribute(pasted_so, "AttributeName");
- CPPUNIT_ASSERT(na2 && na2->Value() == "Some name");
-
-
- //Check method SaveAs
- sm->SaveAs("srn_UnitTest_Save.hdf", study1, false);
- std::string url = study1->URL();
- sm->Close(study1);
-
- //Check method Open
- _PTR(Study) study1_opened = sm->Open("srn_UnitTest_Save.hdf"); //Contains Test component
- system("rm -f srn_UnitTest_Save.hdf");
- url = study1_opened->URL();
- CPPUNIT_ASSERT(study1_opened);
- CPPUNIT_ASSERT(url == "srn_UnitTest_Save.hdf");
-
- //Check method Save
- _PTR(StudyBuilder) sb3 = study1_opened->NewBuilder();
- _PTR(SComponent) sco3 = study1_opened->FindComponent("Test");
- CPPUNIT_ASSERT(sco3);
- // Add a new SObject with AttributeName that contains "Saved study" string
- _PTR(SObject) so3 = sb3->NewObject(sco3);
- std::string soID = so3->GetID();
- _PTR(AttributeName) na3 = sb3->FindOrCreateAttribute(so3, "AttributeName");
- CPPUNIT_ASSERT(na3);
-
- na3->SetValue("Saved study");
-
- // Save and close the study
- sm->Save(study1_opened, false);
-
- sm->Close(study1_opened);
-
- // Open saved study and find the created SObject with AttributeName, then compare the stored string
- _PTR(Study) study2_opened = sm->Open("srn_UnitTest_Save.hdf");
-
- system("rm -f srn_UnitTest_Save.hdf");
-
- CPPUNIT_ASSERT(study2_opened);
-
- _PTR(SObject) so4 = study2_opened->CreateObjectID(soID);
- _PTR(StudyBuilder) sb4 = study2_opened->NewBuilder();
- _PTR(AttributeName) na4 = sb4->FindOrCreateAttribute(so4, "AttributeName");
- CPPUNIT_ASSERT(na4 && na4->Value() == "Saved study"); //Compare the value of restored attribute with string that has to be saved.
-
- //Check method SaveAsASCII
- sm->SaveAsASCII("srn_UnitTest_SaveASCII.hdf", study2_opened, false);
- url = study2_opened->URL();
- sm->Close(study2_opened);
-
- _PTR(Study) study3_opened = sm->Open("srn_UnitTest_SaveASCII.hdf"); //Contains Test component
- system("rm -f srn_UnitTest_SaveASCII.hdf");
- CPPUNIT_ASSERT(study3_opened);
- CPPUNIT_ASSERT(url == "srn_UnitTest_SaveASCII.hdf");
-
- //Check method SaveASCII
- _PTR(StudyBuilder) sb5 = study3_opened->NewBuilder();
- _PTR(SComponent) sco5 = study3_opened->FindComponent("Test");
- CPPUNIT_ASSERT(sco5);
- // Add a new SObject with AttributeName that contains "Saved study" string
- _PTR(SObject) so5 = sb5->NewObject(sco5);
- soID = so5->GetID();
- _PTR(AttributeName) na5 = sb5->FindOrCreateAttribute(so5, "AttributeName");
- CPPUNIT_ASSERT(na5);
- na5->SetValue("Saved study ASCII");
- // Save and close the study
- sm->Save(study3_opened, false);
- sm->Close(study3_opened);
-
- // Open saved study and find the created SObject with AttributeName, then compare the stored string
- _PTR(Study) study4_opened = sm->Open("srn_UnitTest_SaveASCII.hdf");
- system("rm -f srn_UnitTest_SaveASCII.hdf");
- CPPUNIT_ASSERT(study4_opened);
- _PTR(SObject) so6 = study4_opened->CreateObjectID(soID);
- _PTR(StudyBuilder) sb6 = study4_opened->NewBuilder();
- _PTR(AttributeName) na6 = sb6->FindOrCreateAttribute(so6, "AttributeName");
- CPPUNIT_ASSERT(na6 && na6->Value() == "Saved study ASCII"); //Compare the value of restored attribute with string that has to be saved.
-}
-
-
-
void SALOMEDSTest::testUseCase()
{
- //Create or find the Study manager
- _PTR(StudyManager) sm ( new SALOMEDS_StudyManager(_sm) );
- CPPUNIT_ASSERT(sm);
+ //Create Study
+ _PTR(Study) study(new SALOMEDS_Study(_study));
- //Create a new study
- _PTR(Study) study = sm->NewStudy("TestSObject");
CPPUNIT_ASSERT(study);
//Create Study Builder
CPPUNIT_ASSERT(it->More());
CPPUNIT_ASSERT(it->Value()->GetID() == so1->GetID());
- sm->Close(study);
+ study->Clear();
}
#undef SALOMEDS_ALL_TESTS
#include "Basics_Utils.hxx"
#include "SALOME_NamingService.hxx"
#include "NamingService_WaitForServerReadiness.hxx"
-#include "SALOMEDS_StudyManager_i.hxx"
+#include "SALOMEDS_Study_i.hxx"
#ifdef WIN32
#include <winsock2.h>
SALOME_NamingService NS(orb);
if(host.empty())
- NamingService_WaitForServerReadiness(&NS, "/myStudyManager");
+ NamingService_WaitForServerReadiness(&NS, "/Study");
else {
std::string serverName = "/Containers/"+host+"/SuperVisionContainer";
NamingService_WaitForServerReadiness(&NS, serverName);
}
- CORBA::Object_var obj = NS.Resolve( "/myStudyManager" );
+ CORBA::Object_var obj = NS.Resolve( "/Study" );
if(CORBA::is_nil(obj)) {
system("killSalome.py");
return 1;
if(!CORBA::is_nil(poaObj)) {
PortableServer::POA_var poa = PortableServer::POA::_narrow(poaObj);
- SALOMEDS_StudyManager_i * aStudyManager_i = new SALOMEDS_StudyManager_i(orb, 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 aStudyManager_iid = poa->activate_object(aStudyManager_i);
- aStudyManager_i->register_name("/myStudyManager_embedded");
+ PortableServer::ObjectId_var aStudy_iid = poa->activate_object(aStudy_i);
+ SALOMEDS::Study_var Study = aStudy_i->_this();
+ NS.Register(Study.in(), "/Study_embedded");
// Obtain a POAManager, and tell the POA to start accepting
// requests on its objects.
# 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 orbmodule
#include "SALOMEDSClient_SObject.hxx"
#include "SALOMEDSClient_Study.hxx"
#include "SALOMEDSClient_StudyBuilder.hxx"
-#include "SALOMEDSClient_StudyManager.hxx"
#include "SALOMEDSClient_UseCaseBuilder.hxx"
#include "SALOMEDSClient_UseCaseIterator.hxx"
#define SOBJECT_FACTORY "SObjectFactory"
#define SCOMPONENT_FACTORY "SComponentFactory"
#define STUDY_FACTORY "StudyFactory"
+#define STUDY_CREATE "CreateStudy"
#define BUILDER_FACTORY "BuilderFactory"
-#define STUDYMANAGER_FACTORY "StudyManagerFactory"
-#define STUDYMANAGER_CREATE "CreateStudyManager"
#define GET_PARAMETERS "GetIParameters"
#define CONVERT_SOBJECT "ConvertSObject"
-#define CONVERT_STUDY "ConvertStudy"
#define CONVERT_BUILDER "ConvertBuilder"
typedef SALOMEDSClient_SObject* (*SOBJECT_FACTORY_FUNCTION) (SALOMEDS::SObject_ptr);
typedef SALOMEDSClient_SComponent* (*SCOMPONENT_FACTORY_FUNCTION) (SALOMEDS::SComponent_ptr);
typedef SALOMEDSClient_Study* (*STUDY_FACTORY_FUNCTION) (SALOMEDS::Study_ptr);
-typedef SALOMEDSClient_StudyManager* (*STUDYMANAGER_FACTORY_FUNCTION) ();
+typedef void (*STUDY_CREATE_FUNCTION) (CORBA::ORB_ptr, PortableServer::POA_ptr);
typedef SALOMEDSClient_StudyBuilder* (*BUILDER_FACTORY_FUNCTION) (SALOMEDS::StudyBuilder_ptr);
-typedef SALOMEDSClient_StudyManager* (*STUDYMANAGER_CREATE_FUNCTION) (CORBA::ORB_ptr, PortableServer::POA_ptr);
typedef SALOMEDSClient_IParameters* (*GET_PARAMETERS_FACTORY) (const _PTR(AttributeParameter)&);
typedef SALOMEDS::SObject_ptr (*CONVERT_SOBJECT_FUNCTION) (const _PTR(SObject)&);
-typedef SALOMEDS::Study_ptr (*CONVERT_STUDY_FUNCTION) (const _PTR(Study)&);
typedef SALOMEDS::StudyBuilder_ptr (*CONVERT_BUILDER_FUNCTION) (const _PTR(StudyBuilder)&);
static SOBJECT_FACTORY_FUNCTION aSObjectFactory = NULL;
static SCOMPONENT_FACTORY_FUNCTION aSComponentFactory = NULL;
static STUDY_FACTORY_FUNCTION aStudyFactory = NULL;
+static STUDY_CREATE_FUNCTION aCreateFactory = NULL;
static BUILDER_FACTORY_FUNCTION aBuilderFactory = NULL;
-static STUDYMANAGER_FACTORY_FUNCTION aManagerFactory = NULL;
-static STUDYMANAGER_CREATE_FUNCTION aCreateFactory = NULL;
static GET_PARAMETERS_FACTORY aGetIParameters = NULL;
static CONVERT_SOBJECT_FUNCTION aConvertSObject = NULL;
-static CONVERT_STUDY_FUNCTION aConvertStudy = NULL;
static CONVERT_BUILDER_FUNCTION aConvertBuilder = NULL;
_PTR(SObject) ClientFactory::SObject(SALOMEDS::SObject_ptr theSObject)
return _PTR(Study)(study);
}
-_PTR(StudyBuilder) ClientFactory::StudyBuilder(SALOMEDS::StudyBuilder_ptr theStudyBuilder)
-{
- SALOMEDSClient_StudyBuilder* studyBuilder = NULL;
-
-#ifdef WIN32
- if(!_libHandle) _libHandle = ::LoadLibrary(SALOMEDS_LIB_NAME);
- if(!aBuilderFactory) aBuilderFactory = (BUILDER_FACTORY_FUNCTION)::GetProcAddress(_libHandle, BUILDER_FACTORY);
-#else
- if(!_libHandle) _libHandle = dlopen(SALOMEDS_LIB_NAME, RTLD_LAZY | RTLD_GLOBAL);
- if(!aBuilderFactory) aBuilderFactory = (BUILDER_FACTORY_FUNCTION) dlsym(_libHandle, BUILDER_FACTORY);
-#endif
-
- if(aBuilderFactory) studyBuilder = aBuilderFactory(theStudyBuilder);
- return _PTR(StudyBuilder)(studyBuilder);
-}
-
-_PTR(StudyManager) ClientFactory::StudyManager()
+void ClientFactory::createStudy(CORBA::ORB_ptr orb, PortableServer::POA_ptr poa)
{
- SALOMEDSClient_StudyManager* manager = NULL;
-
#ifdef WIN32
if(!_libHandle) _libHandle = ::LoadLibrary(SALOMEDS_LIB_NAME);
- if(!aManagerFactory) aManagerFactory = (STUDYMANAGER_FACTORY_FUNCTION)::GetProcAddress(_libHandle, STUDYMANAGER_FACTORY);
+ if(!aCreateFactory) aCreateFactory = (STUDY_CREATE_FUNCTION)::GetProcAddress(_libHandle, STUDY_CREATE);
#else
if(!_libHandle) _libHandle = dlopen(SALOMEDS_LIB_NAME, RTLD_LAZY | RTLD_GLOBAL);
- if(!aManagerFactory) aManagerFactory = (STUDYMANAGER_FACTORY_FUNCTION) dlsym(_libHandle, STUDYMANAGER_FACTORY);
+ if(!aCreateFactory) aCreateFactory = (STUDY_CREATE_FUNCTION) dlsym(_libHandle, STUDY_CREATE);
#endif
- if(aManagerFactory) manager = aManagerFactory();
- return _PTR(StudyManager)(manager);
+ if(aCreateFactory) aCreateFactory(orb, poa);
}
-_PTR(StudyManager) ClientFactory::createStudyManager(CORBA::ORB_ptr orb, PortableServer::POA_ptr poa)
+_PTR(StudyBuilder) ClientFactory::StudyBuilder(SALOMEDS::StudyBuilder_ptr theStudyBuilder)
{
- SALOMEDSClient_StudyManager* manager = NULL;
+ SALOMEDSClient_StudyBuilder* studyBuilder = NULL;
#ifdef WIN32
if(!_libHandle) _libHandle = ::LoadLibrary(SALOMEDS_LIB_NAME);
- if(!aCreateFactory) aCreateFactory = (STUDYMANAGER_CREATE_FUNCTION)::GetProcAddress(_libHandle, STUDYMANAGER_CREATE);
+ if(!aBuilderFactory) aBuilderFactory = (BUILDER_FACTORY_FUNCTION)::GetProcAddress(_libHandle, BUILDER_FACTORY);
#else
if(!_libHandle) _libHandle = dlopen(SALOMEDS_LIB_NAME, RTLD_LAZY | RTLD_GLOBAL);
- if(!aCreateFactory) aCreateFactory = (STUDYMANAGER_CREATE_FUNCTION) dlsym(_libHandle, STUDYMANAGER_CREATE);
+ if(!aBuilderFactory) aBuilderFactory = (BUILDER_FACTORY_FUNCTION) dlsym(_libHandle, BUILDER_FACTORY);
#endif
- if(aCreateFactory) manager = aCreateFactory(orb, poa);
- return _PTR(StudyManager)(manager);
+ if(aBuilderFactory) studyBuilder = aBuilderFactory(theStudyBuilder);
+ return _PTR(StudyBuilder)(studyBuilder);
}
_PTR(IParameters) ClientFactory::getIParameters(const _PTR(AttributeParameter)& ap)
return so._retn();
}
-
-SALOMEDS::Study_ptr ClientFactory::crbStudy(const _PTR(Study)& theStudy)
-{
- SALOMEDS::Study_var study;
-
-#ifdef WIN32
- if(!_libHandle) _libHandle = ::LoadLibrary(SALOMEDS_LIB_NAME);
- if(!aConvertStudy) aConvertStudy = (CONVERT_STUDY_FUNCTION)::GetProcAddress(_libHandle, CONVERT_STUDY);
-#else
- if(!_libHandle) _libHandle = dlopen(SALOMEDS_LIB_NAME, RTLD_LAZY | RTLD_GLOBAL);
- if(!aConvertStudy) aConvertStudy = (CONVERT_STUDY_FUNCTION) dlsym(_libHandle, CONVERT_STUDY);
-#endif
-
- if(aConvertStudy) study = aConvertStudy(theStudy);
-
- if(CORBA::is_nil(study)) return SALOMEDS::Study::_nil();
- return study._retn();
-}
-
SALOMEDS::StudyBuilder_ptr ClientFactory::crbStudyBuilder(const _PTR(StudyBuilder)& theStudyBuilder)
{
SALOMEDS::StudyBuilder_var studyBuilder;
#include "SALOMEDSClient_SObject.hxx"
#include "SALOMEDSClient_SComponent.hxx"
#include "SALOMEDSClient_Study.hxx"
-#include "SALOMEDSClient_StudyManager.hxx"
#include "SALOMEDSClient_IParameters.hxx"
#include <string>
static _PTR(Study) Study(SALOMEDS::Study_ptr theStudy);
/*!
- * Returns a client StudyBuilder wrapper that corresponds %theStudy
- */
- static _PTR(StudyBuilder) StudyBuilder(SALOMEDS::StudyBuilder_ptr theBuilder);
-
- /*!
- * Returns a client StudyManager wrapper
+ * Creates and returns a client Study wrapper
*/
- static _PTR(StudyManager) StudyManager();
+ static void createStudy(CORBA::ORB_ptr orb, PortableServer::POA_ptr poa);
/*!
- * Creates and returns a client StudyManager wrapper
+ * Returns a client StudyBuilder wrapper that corresponds %theStudy
*/
- static _PTR(StudyManager) createStudyManager(CORBA::ORB_ptr orb, PortableServer::POA_ptr poa);
+ static _PTR(StudyBuilder) StudyBuilder(SALOMEDS::StudyBuilder_ptr theBuilder);
/*!
* Returns an IParameters interface
*/
static SALOMEDS::SObject_ptr crbSObject(const _PTR(SObject)& theSObject);
- /*!
- * Returns a CORBA Study that corresponds %theStudy
- */
- static SALOMEDS::Study_ptr crbStudy(const _PTR(Study)& theStudy);
-
/*!
* Returns a CORBA StudyBuilder that corresponds %theStudyBuilder
*/
/*!
Enables/Disables the dumping visual parameters, static implementation is supposed
*/
- virtual void setDumpPython(_PTR(Study) study, const std::string& theID = "") = 0;
+ virtual void setDumpPython(const std::string& theID = "") = 0;
/*!
Returns whether there is the dumping visual parameters, static implementation is supposed
*/
- virtual bool isDumpPython(_PTR(Study) study, const std::string& theID = "") = 0;
+ virtual bool isDumpPython(const std::string& theID = "") = 0;
/*!
Returns a default name of the component where the visula parameters are stored.
virtual bool FindAttribute(_PTR(GenericAttribute)& anAttribute, const std::string& aTypeOfAttribute) = 0;
virtual bool ReferencedObject(_PTR(SObject)& theObject) = 0;
virtual bool FindSubObject(int theTag, _PTR(SObject)& theObject) = 0;
- virtual _PTR(Study) GetStudy() = 0;
virtual std::string Name() = 0;
virtual void Name(const std::string& theName) = 0;
virtual std::vector<_PTR(GenericAttribute)> GetAllAttributes() = 0;
public:
virtual ~SALOMEDSClient_Study() {}
+ virtual void Init() = 0;
+ virtual void Clear() = 0;
+
+ virtual bool Open(const std::string& theStudyUrl) = 0;
+
virtual std::string GetPersistentReference() = 0;
- virtual std::string GetTransientReference() = 0;
virtual bool IsEmpty() = 0;
virtual _PTR(SComponent) FindComponent (const std::string& aComponentName) = 0;
virtual _PTR(SComponent) FindComponentID(const std::string& aComponentID) = 0;
virtual _PTR(SObject) FindObjectIOR(const std::string& anObjectIOR) = 0;
virtual _PTR(SObject) FindObjectByPath(const std::string& thePath) = 0;
virtual std::string GetObjectPath(const _PTR(SObject)& theSO) = 0;
- virtual void SetContext(const std::string& thePath) = 0;
- virtual std::string GetContext() = 0;
- virtual std::vector<std::string> GetObjectNames(const std::string& theContext) = 0;
- virtual std::vector<std::string> GetDirectoryNames(const std::string& theContext) = 0;
- virtual std::vector<std::string> GetFileNames(const std::string& theContext) = 0;
- virtual std::vector<std::string> GetComponentNames(const std::string& theContext) = 0;
virtual _PTR(ChildIterator) NewChildIterator(const _PTR(SObject)& theSO) = 0;
virtual _PTR(SComponentIterator) NewComponentIterator() = 0;
virtual _PTR(StudyBuilder) NewBuilder() = 0;
virtual std::string Name() = 0;
- virtual void Name(const std::string& name) = 0;
virtual bool IsSaved() = 0;
virtual void IsSaved(bool save) = 0;
virtual bool IsModified() = 0;
virtual void Modified() = 0;
virtual std::string URL() = 0;
virtual void URL(const std::string& url) = 0;
- virtual int StudyId() = 0;
- virtual void StudyId(int id) = 0;
virtual std::vector<_PTR(SObject)> FindDependances(const _PTR(SObject)& theSO) = 0;
virtual _PTR(AttributeStudyProperties) GetProperties() = 0;
virtual std::string GetLastModificationDate() = 0;
virtual std::vector<std::string> GetModificationsDate() = 0;
virtual _PTR(UseCaseBuilder) GetUseCaseBuilder() = 0;
- virtual void Close() = 0;
+
+ virtual bool Save(bool theMultiFile, bool theASCII) = 0;
+ virtual bool SaveAs(const std::string& theUrl, bool theMultiFile, bool theASCII) = 0;
+
+ virtual bool CanCopy(const _PTR(SObject)& theSO) = 0;
+ virtual bool Copy(const _PTR(SObject)& theSO) = 0;
+ virtual bool CanPaste(const _PTR(SObject)& theSO) = 0;
+ virtual _PTR(SObject) Paste(const _PTR(SObject)& theSO) = 0;
+
virtual void EnableUseCaseAutoFilling(bool isEnabled) = 0;
virtual bool DumpStudy(const std::string& thePath,
const std::string& theBaseName,
virtual void RemoveComponent(const _PTR(SComponent)& theSCO) = 0;
virtual _PTR(SObject) NewObject(const _PTR(SObject)& theFatherObject) = 0;
virtual _PTR(SObject) NewObjectToTag(const _PTR(SObject)& theFatherObject, int theTag) = 0;
- virtual void AddDirectory(const std::string& thePath) = 0;
virtual void LoadWith(const _PTR(SComponent)& theSCO, const std::string& theIOR) = 0;
virtual void Load(const _PTR(SObject)& theSCO) = 0;
virtual void RemoveObject(const _PTR(SObject)& theSO) = 0;
+++ /dev/null
-// 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.hxx
-// Author : Sergey RUIN
-// Module : SALOME
-//
-#ifndef __SALOMEDSClient_STUDYMANAGER_H__
-#define __SALOMEDSClient_STUDYMANAGER_H__
-
-#include <vector>
-#include <string>
-
-#include "SALOMEDSClient_definitions.hxx"
-#include "SALOMEDSClient_Study.hxx"
-
-class SALOMEDSClient_StudyManager
-{
-public:
- virtual ~SALOMEDSClient_StudyManager() {}
-
- virtual _PTR(Study) NewStudy(const std::string& study_name) = 0;
- virtual _PTR(Study) Open(const std::string& theStudyUrl) = 0;
- virtual void Close(const _PTR(Study)& theStudy) = 0;
- virtual bool Save(const _PTR(Study)& theStudy, bool theMultiFile) = 0;
- virtual bool SaveASCII(const _PTR(Study)& theStudy, bool theMultiFile) = 0;
- virtual bool SaveAs(const std::string& theUrl, const _PTR(Study)& theStudy, bool theMultiFile) = 0;
- virtual bool SaveAsASCII(const std::string& theUrl, const _PTR(Study)& theStudy, bool theMultiFile) = 0;
- virtual std::vector<std::string> GetOpenStudies() = 0;
- virtual _PTR(Study) GetStudyByName(const std::string& theStudyName) = 0;
- virtual _PTR(Study) GetStudyByID(int theStudyID) = 0;
- virtual bool CanCopy(const _PTR(SObject)& theSO) = 0;
- virtual bool Copy(const _PTR(SObject)& theSO) = 0;
- virtual bool CanPaste(const _PTR(SObject)& theSO) = 0;
- virtual _PTR(SObject) Paste(const _PTR(SObject)& theSO) = 0;
-};
-
-#endif
SALOMEDSImpl_SComponentIterator.cxx
SALOMEDSImpl_StudyBuilder.cxx
SALOMEDSImpl_Study.cxx
- SALOMEDSImpl_StudyManager.cxx
SALOMEDSImpl_IParameters.cxx
SALOMEDSImpl_TMPFile.cxx
SALOMEDSImpl_GenericVariable.cxx
//remove IOR entry in study
if(theValue != myString)
{
- SALOMEDSImpl_Study* study=SALOMEDSImpl_Study::GetStudy(Label());
+ SALOMEDSImpl_Study* study=SALOMEDSImpl_Study::GetStudyImpl(Label());
study->RegisterGenObj(theValue, Label());
study->UnRegisterGenObj(myString, Label());
study->DeleteIORLabelMapItem(myString);
int theObjectID,
const SALOMEDSImpl_SObject& theObject) = 0;
- virtual SALOMEDSImpl_TMPFile* DumpPython(SALOMEDSImpl_Study* theStudy,
- bool isPublished,
+ virtual SALOMEDSImpl_TMPFile* DumpPython(bool isPublished,
bool isMultiFile,
bool& isValidScript,
long& theStreamLength) = 0;
DF_Label aLabel = Label();
if(aLabel.IsNull()) return;
- SALOMEDSImpl_Study* aStudy = SALOMEDSImpl_Study::GetStudy(aLabel);
+ SALOMEDSImpl_Study* aStudy = SALOMEDSImpl_Study::GetStudyImpl(aLabel);
if(!aStudy) return;
if(aStudy->IsLocked()) {
aStudy->_errorCode = "LockProtection";
DF_Label aLabel = Label();
if(aLabel.IsNull()) return;
- SALOMEDSImpl_Study* aStudy = SALOMEDSImpl_Study::GetStudy(aLabel);
+ SALOMEDSImpl_Study* aStudy = SALOMEDSImpl_Study::GetStudyImpl(aLabel);
if(aStudy) aStudy->modifySO_Notification(GetSObject(), reason);
if(aStudy) aStudy->Modify();
}
{
if(!ap) return;
_ap = ap;
- SALOMEDSImpl_SObject so = _ap->GetSObject();
- _study = so.GetStudy();
}
SALOMEDSImpl_IParameters::~SALOMEDSImpl_IParameters()
std::string SALOMEDSImpl_IParameters::decodeEntry(const std::string& entry)
{
- if(!_study) return entry;
int pos = entry.rfind("_");
if(pos < 0 || pos >= entry.size()) return entry;
std::string compName(entry, 0, pos), compID, tail(entry, pos+1, entry.length()-1);
if(_compNames.find(compName) == _compNames.end()) {
- SALOMEDSImpl_SObject so = _study->FindComponent(compName);
+ SALOMEDSImpl_SObject so = SALOMEDSImpl_Study::GetStudyImpl( _ap->GetSObject().GetLabel() )->FindComponent(compName);
if(!so) return entry;
compID = so.GetID();
_compNames[compName] = compID;
dump += shift +"import iparameters\n";
- dump += shift + "ipar = iparameters.IParameters(theStudy.GetModuleParameters(\""+anID+"\", \""+moduleName+"\", 1))\n\n";
+ dump += shift + "ipar = iparameters.IParameters(salome.myStudy.GetModuleParameters(\""+anID+"\", \""+moduleName+"\", 1))\n\n";
std::vector<std::string> v = ip.getProperties();
if(v.size() > 0) {
private:
SALOMEDSImpl_AttributeParameter* _ap;
- SALOMEDSImpl_Study* _study;
std::map<std::string, std::string> _compNames;
};
if(LF.IsRoot()) return sco;
- return GetStudy()->GetSComponent(LF);
+ return SALOMEDSImpl_Study::SComponent(LF);
}
//============================================================================
//============================================================================
SALOMEDSImpl_SObject SALOMEDSImpl_SObject::GetFather() const
{
- return GetStudy()->GetSObject(_lab.Father());
+ return SALOMEDSImpl_Study::SObject(_lab.Father());
}
//============================================================================
return _lab.LastChildTag();
}
-//============================================================================
-/*! Function : GetStudy
- * Purpose :
- */
-//============================================================================
-SALOMEDSImpl_Study* SALOMEDSImpl_SObject::GetStudy() const
-{
- return SALOMEDSImpl_Study::GetStudy(_lab);
-}
-
//============================================================================
/*! Function : FindAttribute
* Purpose : Find attribute of given type on this SObject
if (!(Ref=(SALOMEDSImpl_AttributeReference*)_lab.FindAttribute(SALOMEDSImpl_AttributeReference::GetID())))
return false;
- theObject = GetStudy()->GetSObject(Ref->Get());
+ theObject = SALOMEDSImpl_Study::SObject(Ref->Get());
return true;
}
DF_Label L = _lab.FindChild(theTag, false);
if (L.IsNull()) return false;
- theObject = GetStudy()->GetSObject(L);
+ theObject = SALOMEDSImpl_Study::SObject(L);
return true;
}
virtual bool ReferencedObject(SALOMEDSImpl_SObject& theObject) const ;
virtual bool FindSubObject(int theTag, SALOMEDSImpl_SObject& theObject);
- virtual SALOMEDSImpl_Study* GetStudy() const;
virtual std::string Name() const { return _name; }
virtual void Name(const std::string& theName) { _name = theName; }
virtual std::vector<DF_Attribute*> GetAllAttributes() const;
#include <KERNEL_version.h>
#include <Basics_Utils.hxx>
+#include <Basics_DirUtils.hxx>
+
+#include "HDFexplorer.hxx"
#include "DF_Application.hxx"
#include "DF_ChildIterator.hxx"
#include "SALOMEDSImpl_Tool.hxx"
#include "SALOMEDSImpl_IParameters.hxx"
#include "SALOMEDSImpl_ScalarVariable.hxx"
+#include "SALOMEDSImpl_SComponent.hxx"
+#include "HDFOI.hxx"
#include <fstream>
#include <sstream>
#include <algorithm>
#define FILEID "FILE: "
#define VARIABLE_SEPARATOR ':'
#define OPERATION_SEPARATOR '|'
+#define USE_CASE_LABEL_ID "0:2"
+
+static void SaveAttributes(const SALOMEDSImpl_SObject& SO, HDFgroup *hdf_group_sobject);
+static void ReadAttributes(SALOMEDSImpl_Study*, const SALOMEDSImpl_SObject&, HDFdataset* );
+static void BuildTree (SALOMEDSImpl_Study*, HDFgroup*);
+static void Translate_IOR_to_persistentID (const SALOMEDSImpl_SObject&,
+ SALOMEDSImpl_Driver*, bool isMultiFile, bool isASCII);
+static void ReadNoteBookVariables(SALOMEDSImpl_Study* theStudy, HDFgroup* theGroup);
+
+namespace {
+ class StudyUnlocker
+ {
+ public:
+ StudyUnlocker( SALOMEDSImpl_Study* study ): myStudy( study ), myLocked( false )
+ {
+ myPrevLocked = myStudy->GetProperties()->IsLocked();
+ resume();
+ }
+ ~StudyUnlocker()
+ {
+ suspend();
+ }
+ void suspend()
+ {
+ if (myLocked) {
+ myStudy->GetProperties()->SetLocked(true);
+ myPrevLocked = myLocked;
+ myLocked = false;
+ }
+ }
+ void resume()
+ {
+ if (myPrevLocked) {
+ myStudy->GetProperties()->SetLocked(false);
+ myLocked = myPrevLocked;
+ myPrevLocked = false;
+ }
+ }
+ private:
+ SALOMEDSImpl_Study* myStudy;
+ bool myLocked;
+ bool myPrevLocked;
+ };
+}
//============================================================================
/*! Function : SALOMEDSImpl_Study
* Purpose : SALOMEDSImpl_Study constructor
*/
//============================================================================
-SALOMEDSImpl_Study::SALOMEDSImpl_Study(const DF_Document* doc,
- const std::string& study_name)
+SALOMEDSImpl_Study::SALOMEDSImpl_Study()
+{
+ _appli = new DF_Application();
+ _clipboard = _appli->NewDocument("SALOME_STUDY");
+
+ Init();
+}
+
+//============================================================================
+/*! Function : ~SALOMEDSImpl_Study
+ * Purpose : SALOMEDSImpl_Study destructor
+ */
+//============================================================================
+SALOMEDSImpl_Study::~SALOMEDSImpl_Study()
+{
+ Clear();
+ _appli->Close(_clipboard);
+ // Destroy application
+ delete _appli;
+}
+
+//============================================================================
+/*! Function : Init
+ * Purpose : Initialize study components
+ */
+//============================================================================
+void SALOMEDSImpl_Study::Init()
{
- _name = study_name;
- _doc = (DF_Document*)doc;
- _Saved = false ;
+ static int _id = 0;
+ std::stringstream sstrm;
+ sstrm << ++_id;
+ _name = "Study" + std::string(sstrm.str());
+ _doc = _appli->NewDocument("SALOME_STUDY");
+ _Saved = false;
_URL = "";
- _StudyId = -1;
_autoFill = false;
_errorCode = "";
_useCaseBuilder = new SALOMEDSImpl_UseCaseBuilder(_doc);
//Put on the root label a StudyHandle attribute to store the address of this object
//It will be used to retrieve the study object by DF_Label that belongs to the study
SALOMEDSImpl_StudyHandle::Set(_doc->Main().Root(), this);
-}
+ // set Study properties
+ SALOMEDSImpl_AttributeStudyProperties* aProp = GetProperties();
+
+ int month=0,day=0,year=0,hh=0,mn=0,ss=0;
+ SALOMEDSImpl_Tool::GetSystemDate(year, month, day, hh, mn, ss);
+ aProp->SetModification(SALOMEDSImpl_Tool::GetUserName(),
+ mn, hh, day, month, year);
+ aProp->SetCreationMode(1); //"from scratch"
+}
//============================================================================
-/*! Function : ~SALOMEDSImpl_Study
- * Purpose : SALOMEDSImpl_Study destructor
+/*! Function : Clear
+ * Purpose : Clear study components
*/
//============================================================================
-SALOMEDSImpl_Study::~SALOMEDSImpl_Study()
+void SALOMEDSImpl_Study::Clear()
{
delete _builder;
delete _cb;
delete _useCaseBuilder;
+ URL("");
+ _appli->Close(_doc);
+ _doc = NULL;
+ _mapOfSO.clear();
+ _mapOfSCO.clear();
}
//============================================================================
-/*! Function : GetPersistentReference
- * Purpose : Get persistent reference of study (idem URL())
+/*! Function : Open
+ * Purpose : Open a Study from it's persistent reference
*/
//============================================================================
-std::string SALOMEDSImpl_Study::GetPersistentReference()
+bool SALOMEDSImpl_Study::Open(const std::string& aUrl)
{
+ // Set "C" locale temporarily to avoid possible localization problems
+ Kernel_Utils::Localizer loc;
+
_errorCode = "";
- return URL();
+
+ // open the HDFFile
+ HDFfile *hdf_file =0;
+ HDFgroup *hdf_group_study_structure =0;
+ HDFgroup *hdf_notebook_vars = 0;
+
+ char* aC_HDFUrl;
+ std::string aHDFUrl;
+ bool isASCII = false;
+ if (HDFascii::isASCII(aUrl.c_str())) {
+ isASCII = true;
+ char* aResultPath = HDFascii::ConvertFromASCIIToHDF(aUrl.c_str());
+ if ( !aResultPath )
+ return NULL;
+ aC_HDFUrl = new char[strlen(aResultPath) + 19];
+ sprintf(aC_HDFUrl, "%shdf_from_ascii.hdf", aResultPath);
+ delete [] (aResultPath);
+ aHDFUrl = aC_HDFUrl;
+ delete [] aC_HDFUrl;
+ }
+ else {
+ aHDFUrl = aUrl;
+ }
+
+ hdf_file = new HDFfile((char*)aHDFUrl.c_str());
+ try {
+ hdf_file->OpenOnDisk(HDF_RDONLY);// mpv: was RDWR, but opened file can be write-protected too
+ }
+ catch (HDFexception)
+ {
+ char *eStr;
+ eStr = new char[strlen(aUrl.c_str())+17];
+ sprintf(eStr,"Can't open file %s",aUrl.c_str());
+ delete [] eStr;
+ _errorCode = std::string(eStr);
+ return NULL;
+ }
+
+ // Assign the value of the URL in the study object
+ URL(aUrl);
+
+ SALOMEDSImpl_AttributePersistentRef::Set(_doc->Main(), aUrl);
+
+ if (!hdf_file->ExistInternalObject("STUDY_STRUCTURE")) {
+ _errorCode = "Study is empty";
+ return false;
+ }
+
+ //Create the Structure of the Document
+ hdf_group_study_structure = new HDFgroup("STUDY_STRUCTURE",hdf_file);
+
+ try {
+ BuildTree (this, hdf_group_study_structure);
+ }
+ catch (HDFexception)
+ {
+ char *eStr = new char [strlen(aUrl.c_str())+17];
+ sprintf(eStr,"Can't open file %s", aUrl.c_str());
+ _errorCode = std::string(eStr);
+ return false;
+ }
+
+ //Read and create notebook variables
+ if(hdf_file->ExistInternalObject("NOTEBOOK_VARIABLES")) {
+ hdf_notebook_vars = new HDFgroup("NOTEBOOK_VARIABLES",hdf_file);
+ ReadNoteBookVariables(this, hdf_notebook_vars);
+ hdf_notebook_vars =0; //will be deleted by hdf_sco_group destructor
+ }
+
+ hdf_file->CloseOnDisk();
+ hdf_group_study_structure = new HDFgroup("STUDY_STRUCTURE",hdf_file);
+
+ if (isASCII) {
+ std::vector<std::string> aFilesToRemove;
+ aFilesToRemove.push_back("hdf_from_ascii.hdf");
+ SALOMEDSImpl_Tool::RemoveTemporaryFiles(SALOMEDSImpl_Tool::GetDirFromPath(aHDFUrl), aFilesToRemove, true);
+ }
+
+ delete hdf_file; // all related hdf objects will be deleted
+
+ // unlock study if it is locked, to set components versions
+ StudyUnlocker unlock(this);
+
+ //For old studies we have to add "unknown" version tag for all stored components
+ SALOMEDSImpl_SComponentIterator itcomponent = NewComponentIterator();
+ for (; itcomponent.More(); itcomponent.Next())
+ {
+ SALOMEDSImpl_SComponent sco = itcomponent.Value();
+ std::string aCompType = sco.GetComment();
+ if ( aCompType == SALOMEDSImpl_IParameters::getDefaultVisualComponent() ) continue;
+ if ( GetProperties()->GetComponentVersions( aCompType ).empty() )
+ GetProperties()->SetComponentVersion( aCompType, "" ); // empty version means "unknown"
+ }
+
+ return true;
}
+
//============================================================================
-/*! Function : GetTransientReference
- * Purpose : Get IOR of the Study (registred in Document in doc->Root)
+/*! Function : Save
+ * Purpose : Save a Study to it's persistent reference
*/
//============================================================================
-std::string SALOMEDSImpl_Study::GetTransientReference()
+bool SALOMEDSImpl_Study::Save(SALOMEDSImpl_DriverFactory* aFactory,
+ bool theMultiFile,
+ bool theASCII)
{
_errorCode = "";
- std::string IOR = "";
- SALOMEDSImpl_AttributeIOR* Att;
- DF_Label _lab = _doc->Root();
- if ((Att=(SALOMEDSImpl_AttributeIOR*)_lab.FindAttribute(SALOMEDSImpl_AttributeIOR::GetID()))) {
- IOR = Att->Value();
+ std::string url = URL();
+ if (url.empty()) {
+ _errorCode = "No path specified to save the study. Nothing done";
+ return false;
}
else {
- _errorCode = "IOR is empty";
+ return Impl_SaveAs(url, aFactory, theMultiFile, theASCII);
}
- return IOR;
+ return false;
+}
+
+//=============================================================================
+/*! Function : SaveAs
+ * Purpose : Save a study to the persistent reference aUrl
+ */
+//============================================================================
+bool SALOMEDSImpl_Study::SaveAs(const std::string& aUrl,
+ SALOMEDSImpl_DriverFactory* aFactory,
+ bool theMultiFile,
+ bool theASCII)
+{
+ _errorCode = "";
+ return Impl_SaveAs(aUrl, aFactory, theMultiFile, theASCII);
}
-void SALOMEDSImpl_Study::SetTransientReference(const std::string& theIOR)
+//=============================================================================
+/*! Function : _SaveProperties
+ * Purpose : save the study properties in HDF file
+ */
+//============================================================================
+bool SALOMEDSImpl_Study::Impl_SaveProperties(HDFgroup *hdf_group)
{
_errorCode = "";
+ HDFdataset *hdf_dataset = 0;
+ hdf_size size[1];
+ hdf_int32 name_len;
+
+ // add modifications list (user and date of save)
SALOMEDSImpl_AttributeStudyProperties* aProp = GetProperties();
- int aLocked = aProp->IsLocked();
- if (aLocked) aProp->SetLocked(false);
- // Assign the value of the IOR in the study->root
- SALOMEDSImpl_AttributeIOR::Set(_doc->Main().Root(), theIOR);
+ // unlock study if it is locked, to set modification date
+ StudyUnlocker unlock(this);
+
+ int month=0,day=0,year=0,hh=0,mn=0,ss=0;
+ SALOMEDSImpl_Tool::GetSystemDate(year, month, day, hh, mn, ss);
+ aProp->SetModification(SALOMEDSImpl_Tool::GetUserName(),
+ mn, hh, day, month, year);
+
+ // lock study back if it was locked initially, to write correct value of Locked flag
+ unlock.suspend();
+
+ std::vector<std::string> aNames;
+ std::vector<int> aMinutes, aHours, aDays, aMonths, aYears;
+
+ aProp->GetModifications(aNames, aMinutes, aHours, aDays, aMonths, aYears);
+
+ std::string units = aProp->GetUnits();
+ std::string comment = aProp->GetComment();
+
+ std::map< std::string, std::vector<std::string> > allVersions = aProp->GetComponentsVersions();
+ std::map<std::string, std::string> versions;
+
+ int aLength = 0, aLength1 = 0, anIndex, i, unitsSize = 0, commentSize = 0;
+
+ for(i=1; i<=aNames.size(); i++)
+ aLength += aNames[i-1].size() + 1;
+
+ std::map< std::string, std::vector<std::string> >::const_iterator it;
+ for (it = allVersions.begin(); it != allVersions.end(); ++it ) {
+ std::string vlist = "";
+ std::vector<std::string> vl = it->second;
+ std::vector<std::string>::const_iterator vlit;
+ for ( vlit = vl.begin(); vlit != vl.end(); ++vlit ) {
+ if ( vlist != "" ) vlist += ";";
+ vlist += *vlit;
+ }
+ versions[ it->first ] = vlist;
+ aLength1 += it->first.size() + vlist.size() + 2;
+ }
+
+ unitsSize = units.size();
+ commentSize = comment.size();
+
+ //string format:
+ //locked flag, modified flag,
+ //minutes, hours, day, months, year, user name, char(1),
+ //minutes, hours, day, months, year, user name, char(1),
+ //.....................................................,
+ //.....................................................,
+ //.....................................................,
+ //minutes, hours, day, months, year, user name, char(1), char(30) <- !!!! used to define end of section with modifications !!!!
+ //units, char(1), comment, char(30) <- !!!! used to define start of section with components' versions !!!!
+ //component=versions, char(1),
+ //component=versions, char(1),
+ //...........................,
+ //component=versions, char(1), char(0)
+
+ //string length: 1 byte = locked flag, 1 byte = modified flag, (12 + name length + 1) for each name and date, 1 byte (char(30) section delimeter)
+ // unit length + 1, comment length, "zero" byte
+
+ char* aProperty = new char[3 + aLength + 12 * aNames.size() + 1 + unitsSize + 1 + commentSize + 1 + aLength1 ];
+
+ sprintf(aProperty,"%c%c", (char)aProp->GetCreationMode(), (aProp->IsLocked())?'l':'u');
+
+ aLength = aNames.size();
+ int a = 2;
+ for(anIndex = 0; anIndex<aLength; anIndex++) {
+ sprintf(&(aProperty[a]),"%2d%2d%2d%2d%4d%s",
+ (int)(aMinutes[anIndex]),
+ (int)(aHours[anIndex]),
+ (int)(aDays[anIndex]),
+ (int)(aMonths[anIndex]),
+ (int)(aYears[anIndex]),
+ aNames[anIndex].c_str());
+ a = strlen(aProperty);
+ aProperty[a++] = 1;
+ }
+
+ //Write delimeter of the section to define end of the modifications section
+ aProperty[a++] = 30;
+
+ //Write units if need
+ if(units.size() > 0) {
+ sprintf(&(aProperty[a]),"%s",units.c_str());
+ a = strlen(aProperty);
+ }
+
+ aProperty[a++] = 1;
+
+ //Write comments if need
+ if(comment.size() > 0) {
+ sprintf(&(aProperty[a]),"%s",comment.c_str());
+ a = strlen(aProperty);
+ }
+
+ aProperty[a++] = 30; //delimeter of the component versions
+
+ std::map<std::string, std::string>::const_iterator versionsIt;
+ for ( versionsIt = versions.begin(); versionsIt != versions.end(); ++versionsIt ) {
+ sprintf(&(aProperty[a]),"%s=%s",
+ (char*)(versionsIt->first.c_str()),
+ (char*)(versionsIt->second.c_str()));
+ a = a + versionsIt->first.size() + versionsIt->second.size() + 1;
+ aProperty[a++] = 1;
+ }
+
+ aProperty[a] = 0;
+
+ name_len = (hdf_int32) a;
+ size[0] = name_len + 1 ;
+ hdf_dataset = new HDFdataset("AttributeStudyProperties",hdf_group,HDF_STRING,size,1);
+ hdf_dataset->CreateOnDisk();
+ hdf_dataset->WriteOnDisk(aProperty);
+ hdf_dataset->CloseOnDisk();
+ hdf_dataset=0; //will be deleted by hdf_sco_group destructor
+ delete [] aProperty;
+
+ aProp->SetModified(0);
+ return true;
+}
+
+//=============================================================================
+/*! Function : _SaveAs
+ * Purpose : save the study in HDF file
+ */
+//============================================================================
+bool SALOMEDSImpl_Study::Impl_SaveAs(const std::string& aStudyUrl,
+ SALOMEDSImpl_DriverFactory* aFactory,
+ bool theMultiFile,
+ bool theASCII)
+{
+ // Set "C" locale temporarily to avoid possible localization problems
+ Kernel_Utils::Localizer loc;
+
+ // HDF File will be composed of differents part :
+ // * For each ComponentDataType, all data created by the component
+ // Informations in data group hdf_group_datacomponent
+ // * Study Structure -> Exactly what is contained in Document
+ // Informations in data group hdf_group_study_structure
+
+ _errorCode = "";
+
+ HDFfile *hdf_file=0;
+ HDFgroup *hdf_group_study_structure =0;
+ HDFgroup *hdf_sco_group =0;
+ HDFgroup *hdf_sco_group2 =0;
+ HDFgroup *hdf_notebook_vars =0;
+ HDFgroup *hdf_notebook_var = 0;
+
+ HDFgroup *hdf_group_datacomponent =0;
+ HDFdataset *hdf_dataset =0;
+ hdf_size size[1];
+ hdf_int32 name_len = 0;
+ std::string component_name;
+
+ // Store previous URL
+ std::string anOldName = URL();
+
+ // Map to store components' versions
+ std::map<std::string, std::string> componentVersions;
+
+ //Create a temporary url to which the study is saved
+ std::string aUrl = SALOMEDSImpl_Tool::GetTmpDir() + SALOMEDSImpl_Tool::GetNameFromPath(aStudyUrl);
+
+ // unlock study if it is locked, as some attributes need to be modified
+ StudyUnlocker unlock(this);
+
+ SALOMEDSImpl_StudyBuilder* SB= NewBuilder();
+ std::map<std::string, SALOMEDSImpl_Driver*> aMapTypeDriver;
+
+ try {
+ // mpv 15.12.2003: for saving components we have to load all data from all modules
+ SALOMEDSImpl_SComponentIterator itcomponent = NewComponentIterator();
+ for (; itcomponent.More(); itcomponent.Next()) {
+ SALOMEDSImpl_SComponent sco = itcomponent.Value();
+ // if there is an associated Engine call its method for saving
+ std::string IOREngine;
+ try {
+ SALOMEDSImpl_Driver* aDriver = NULL;
+ std::string aCompType = sco.GetComment();
+ if (!sco.ComponentIOR(IOREngine)) {
+ if (!aCompType.empty()) {
+ aDriver = aFactory->GetDriverByType(aCompType);
+ if (aDriver != NULL) {
+ if (!SB->LoadWith(sco, aDriver)) {
+ _errorCode = SB->GetErrorCode();
+ return false;
+ }
+ }
+ }
+ }
+ else {
+ aDriver = aFactory->GetDriverByIOR(IOREngine);
+ }
+ aMapTypeDriver[aCompType] = aDriver;
+ }
+ catch(...) {
+ _errorCode = "Can not restore information to resave it";
+ return false;
+ }
+ }
+
+ // VSR: set URL to new file name
+ // VSR: remember to set previous name if save operation fails
+ URL(aStudyUrl);
+
+ // To change for Save
+ // Do not have to do a new file but just a Open??? Rewrite all informations after erasing evrything??
+ hdf_file = new HDFfile((char*)aUrl.c_str());
+ hdf_file->CreateOnDisk();
+
+ //-----------------------------------------------------------------------
+ // 1 - Create a groupe for each SComponent and Update the PersistanceRef
+ //-----------------------------------------------------------------------
+ hdf_group_datacomponent = new HDFgroup("DATACOMPONENT",hdf_file);
+ hdf_group_datacomponent->CreateOnDisk();
+
+ for (itcomponent.Init(); itcomponent.More(); itcomponent.Next()) {
+ SALOMEDSImpl_SComponent sco = itcomponent.Value();
+
+ std::string scoid = sco.GetID();
+ hdf_sco_group = new HDFgroup((char*)scoid.c_str(), hdf_group_datacomponent);
+ hdf_sco_group->CreateOnDisk();
+
+ std::string componentDataType = sco.ComponentDataType();
+ std::string IOREngine;
+ if (sco.ComponentIOR(IOREngine)) {
+ // Engine should be already in the map as it was to added before
+ SALOMEDSImpl_Driver* Engine = aMapTypeDriver[componentDataType];
+ if (Engine != NULL) {
+ SALOMEDSImpl_TMPFile* aStream = NULL;
+ long length = 0;
+
+ componentVersions[ componentDataType ] = Engine->Version();
+
+ if (theASCII) aStream = Engine->SaveASCII(sco,
+ SALOMEDSImpl_Tool::GetDirFromPath(aUrl),
+ length,
+ theMultiFile);
+ else aStream = Engine->Save(sco,
+ SALOMEDSImpl_Tool::GetDirFromPath(aUrl),
+ length,
+ theMultiFile);
+ HDFdataset *hdf_dataset;
+ hdf_size aHDFSize[1];
+ if (length > 0) { //The component saved some auxiliary files, then put them into HDF file
+ aHDFSize[0] = length;
+
+ HDFdataset *hdf_dataset = new HDFdataset("FILE_STREAM", hdf_sco_group, HDF_STRING, aHDFSize, 1);
+ hdf_dataset->CreateOnDisk();
+ hdf_dataset->WriteOnDisk(aStream->Data()); //Save the stream in the HDF file
+ hdf_dataset->CloseOnDisk();
+ }
+
+ if (aStream) delete aStream;
+
+ // store multifile state
+ aHDFSize[0] = 2;
+ hdf_dataset = new HDFdataset("MULTIFILE_STATE", hdf_sco_group, HDF_STRING, aHDFSize, 1);
+ hdf_dataset->CreateOnDisk();
+ hdf_dataset->WriteOnDisk((void*)(theMultiFile?"M":"S")); // save: multi or single
+ hdf_dataset->CloseOnDisk();
+ hdf_dataset=0; //will be deleted by hdf_sco_AuxFiles destructor
+ // store ASCII state
+ aHDFSize[0] = 2;
+ hdf_dataset = new HDFdataset("ASCII_STATE", hdf_sco_group, HDF_STRING, aHDFSize, 1);
+ hdf_dataset->CreateOnDisk();
+ hdf_dataset->WriteOnDisk((void*)(theASCII?"A":"B")); // save: ASCII or BINARY
+ hdf_dataset->CloseOnDisk();
+ hdf_dataset=0; //will be deleted by hdf_sco_AuxFiles destructor
+ // Creation of the persistance reference attribute
+ Translate_IOR_to_persistentID (sco, Engine, theMultiFile, theASCII);
+ }
+ }
+ hdf_sco_group->CloseOnDisk();
+ hdf_sco_group=0; // will be deleted by hdf_group_datacomponent destructor
+ }
+ hdf_group_datacomponent->CloseOnDisk();
+ hdf_group_datacomponent =0; // will be deleted by hdf_file destructor
+
+ //-----------------------------------------------------------------------
+ //3 - Write the Study Structure
+ //-----------------------------------------------------------------------
+ hdf_group_study_structure = new HDFgroup("STUDY_STRUCTURE",hdf_file);
+ hdf_group_study_structure->CreateOnDisk();
+ // save component attributes
+ for (itcomponent.Init(); itcomponent.More(); itcomponent.Next()) {
+ SALOMEDSImpl_SComponent SC = itcomponent.Value();
+ std::string scid = SC.GetID();
+ hdf_sco_group2 = new HDFgroup((char*)scid.c_str(), hdf_group_study_structure);
+ hdf_sco_group2->CreateOnDisk();
+ SaveAttributes(SC, hdf_sco_group2);
+ // ComponentDataType treatment
+ component_name = SC.ComponentDataType();
+ name_len = (hdf_int32)component_name.length();
+ size[0] = name_len +1 ;
+ hdf_dataset = new HDFdataset("COMPONENTDATATYPE",hdf_sco_group2,HDF_STRING,size,1);
+ hdf_dataset->CreateOnDisk();
+ hdf_dataset->WriteOnDisk((char*)component_name.c_str());
+ hdf_dataset->CloseOnDisk();
+ hdf_dataset=0; //will be deleted by hdf_sco_group destructor
+ Impl_SaveObject(SC, hdf_sco_group2);
+ hdf_sco_group2->CloseOnDisk();
+ hdf_sco_group2=0; // will be deleted by hdf_group_study_structure destructor
+ }
+ //-----------------------------------------------------------------------
+ //4 - Write the Study UseCases Structure
+ //-----------------------------------------------------------------------
+ SALOMEDSImpl_SObject aSO = FindObjectID(USE_CASE_LABEL_ID);
+ if (aSO) {
+ HDFgroup *hdf_soo_group = new HDFgroup(USE_CASE_LABEL_ID,hdf_group_study_structure);
+ hdf_soo_group->CreateOnDisk();
+ SaveAttributes(aSO, hdf_soo_group);
+ Impl_SaveObject(aSO, hdf_soo_group);
+ hdf_soo_group->CloseOnDisk();
+ hdf_soo_group=0; // will be deleted by hdf_group_study_structure destructor
+ }
+ //-----------------------------------------------------------------------
+ //5 - Write the NoteBook Variables
+ //-----------------------------------------------------------------------
+
+ //5.1 Create group to store all note book variables
+ hdf_notebook_vars = new HDFgroup("NOTEBOOK_VARIABLES",hdf_file);
+ hdf_notebook_vars->CreateOnDisk();
+
+ std::string varValue;
+ std::string varType;
+ std::string varIndex;
+
+ for (int i=0 ;i < myNoteBookVars.size(); i++ ) {
+ // For each variable create HDF group
+ hdf_notebook_var = new HDFgroup((char*)myNoteBookVars[i]->Name().c_str(),hdf_notebook_vars);
+ hdf_notebook_var->CreateOnDisk();
+
+ // Save Variable type
+ varType = myNoteBookVars[i]->SaveType();
+ name_len = (hdf_int32) varType.length();
+ size[0] = name_len +1 ;
+ hdf_dataset = new HDFdataset("VARIABLE_TYPE",hdf_notebook_var,HDF_STRING,size,1);
+ hdf_dataset->CreateOnDisk();
+ hdf_dataset->WriteOnDisk((char*)varType.c_str());
+ hdf_dataset->CloseOnDisk();
+ hdf_dataset=0; //will be deleted by hdf_sco_group destructor
+
+ char buffer[256];
+ sprintf(buffer,"%d",i);
+ varIndex= std::string(buffer);
+ name_len = (hdf_int32) varIndex.length();
+ size[0] = name_len +1 ;
+ hdf_dataset = new HDFdataset("VARIABLE_INDEX",hdf_notebook_var,HDF_STRING,size,1);
+ hdf_dataset->CreateOnDisk();
+ hdf_dataset->WriteOnDisk((char*)varIndex.c_str());
+ hdf_dataset->CloseOnDisk();
+ hdf_dataset=0; //will be deleted by hdf_sco_group destructor
+
+ // Save Variable value
+ varValue = myNoteBookVars[i]->Save();
+ name_len = (hdf_int32) varValue.length();
+ size[0] = name_len +1 ;
+ hdf_dataset = new HDFdataset("VARIABLE_VALUE",hdf_notebook_var,HDF_STRING,size,1);
+ hdf_dataset->CreateOnDisk();
+ hdf_dataset->WriteOnDisk((char*)varValue.c_str());
+ hdf_dataset->CloseOnDisk();
+ hdf_dataset=0; //will be deleted by hdf_sco_group destructor
+ hdf_notebook_var->CloseOnDisk();
+ hdf_notebook_var = 0; //will be deleted by hdf_sco_group destructor
+ }
+ hdf_notebook_vars->CloseOnDisk();
+ hdf_notebook_vars = 0; //will be deleted by hdf_sco_group destructor
+
+ // record component versions
+ std::map<std::string, std::string>::const_iterator itVersions;
+ for ( itVersions = componentVersions.begin(); itVersions != componentVersions.end(); ++itVersions )
+ GetProperties()->SetComponentVersion( itVersions->first, itVersions->second );
+
+ // lock study back if it was locked initially, to write correct value of Locked flag
+ unlock.suspend();
+
+ //-----------------------------------------------------------------------
+ //6 - Write the Study Properties
+ //-----------------------------------------------------------------------
+ std::string study_name = Name();
+ name_len = (hdf_int32) study_name.size();
+ size[0] = name_len +1 ;
+ hdf_dataset = new HDFdataset("STUDY_NAME",hdf_group_study_structure,HDF_STRING,size,1);
+ hdf_dataset->CreateOnDisk();
+ hdf_dataset->WriteOnDisk((char*)study_name.c_str());
+ hdf_dataset->CloseOnDisk();
+ hdf_dataset=0; // will be deleted by hdf_group_study_structure destructor
+
+ Impl_SaveProperties(hdf_group_study_structure);
+ hdf_group_study_structure->CloseOnDisk();
+ hdf_file->CloseOnDisk();
+
+ hdf_group_study_structure =0; // will be deleted by hdf_file destructor
+ delete hdf_file; // recursively deletes all hdf objects...
+ }
+ catch (HDFexception) {
+ _errorCode = "HDFexception ! ";
+ URL( anOldName ); // VSR: restore previous url if operation is failed
+ return false;
+ }
+ catch (std::exception& exc) {
+ _errorCode = const_cast<char*>(exc.what());
+ URL( anOldName ); // VSR: restore previous url if operation is failed
+ return false;
+ }
+ catch (...) {
+ _errorCode = "Unknown exception ! ";
+ URL( anOldName ); // VSR: restore previous url if operation is failed
+ return false;
+ }
+ if (theASCII) { // save file in ASCII format
+ HDFascii::ConvertFromHDFToASCII(aUrl.c_str(), true);
+ }
+
+ // Now it's necessary to copy files from the temporary directory to the user defined directory.
+ // The easiest way to get a list of file in the temporary directory
+
+ std::string aCmd, aTmpFileDir = SALOMEDSImpl_Tool::GetTmpDir();
+ std::string aTmpFile = aTmpFileDir +"files";
+ std::string aStudyTmpDir = SALOMEDSImpl_Tool::GetDirFromPath(aUrl);
+
+#ifdef WIN32
+ aCmd = "dir /B \"" + aStudyTmpDir +"\" > " + aTmpFile;
+#else
+ aCmd ="ls -1 \"" + aStudyTmpDir +"\" > " + aTmpFile;
+#endif
+ system(aCmd.c_str());
+
+ // Iterate and move files in the temporary directory
+ FILE* fp = fopen(aTmpFile.c_str(), "rb");
+ if (!fp) {
+ URL( anOldName ); // VSR: restore previous url if operation is failed
+ return false;
+ }
+ char* buffer = new char[2047];
+ int errors = 0;
+ while (!feof(fp) && !errors) {
+ if ((fgets(buffer, 2046, fp)) == NULL) break;
+ size_t aLen = strlen(buffer);
+ if (buffer[aLen-1] == '\n') buffer[aLen-1] = char(0);
+#ifdef WIN32
+ aCmd = "move /Y \"" + aStudyTmpDir + std::string(buffer) + "\" \"" + SALOMEDSImpl_Tool::GetDirFromPath(aStudyUrl) +"\"";
+#else
+ aCmd = "mv -f \"" + aStudyTmpDir + std::string(buffer) + "\" \"" + SALOMEDSImpl_Tool::GetDirFromPath(aStudyUrl)+"\"";
+#endif
+ errors = system(aCmd.c_str());
+ }
+
+ delete []buffer;
+ fclose(fp);
+
+ // Perform cleanup
+#ifdef WIN32
+ DeleteFileA(aTmpFile.c_str());
+#else
+ unlink(aTmpFile.c_str());
+#endif
+
+#ifdef WIN32
+ RemoveDirectoryA(aTmpFileDir.c_str());
+ RemoveDirectoryA(aStudyTmpDir.c_str());
+#else
+ rmdir(aTmpFileDir.c_str());
+ rmdir(aStudyTmpDir.c_str());
+#endif
+
+ if ( !errors ) {
+ // VSR: finally, if all is done without errors, mark study as Saved
+ IsSaved(true);
+ }
+
+ return !errors;
+}
+
+//============================================================================
+/*! Function : Impl_SaveObject
+ * Purpose :
+ */
+//============================================================================
+bool SALOMEDSImpl_Study::Impl_SaveObject(const SALOMEDSImpl_SObject& SC,
+ HDFgroup *hdf_group_datatype)
+{
+ _errorCode = "";
+
+ // Write in group hdf_group_datatype all informations of SObject SC
+ // Iterative function to parse all SObjects under a SComponent
+
+ HDFgroup *hdf_group_sobject = 0;
+
+ DF_ChildIterator itchild(SC.GetLabel());
+ for (; itchild.More(); itchild.Next()) {
+ // mpv: don't save empty labels
+ std::vector<DF_Attribute*> attr = itchild.Value().GetAttributes();
+ if (attr.size() == 0) { //No attributes on the label
+ DF_ChildIterator subchild(itchild.Value());
+ if (!subchild.More()) {
+ continue;
+ }
+ subchild.Init(itchild.Value(), true);
+ bool anEmpty = true;
+ for (; subchild.More() && anEmpty; subchild.Next()) {
+ std::vector<DF_Attribute*> attr2 = subchild.Value().GetAttributes();
+ if (attr2.size()) {
+ anEmpty = false; //There are attributes on the child label
+ break;
+ }
+ }
+ if (anEmpty) continue;
+ }
+
+ SALOMEDSImpl_SObject SO = SALOMEDSImpl_Study::SObject(itchild.Value());
+
+ std::string scoid = SO.GetID();
+ hdf_group_sobject = new HDFgroup(scoid.c_str(), hdf_group_datatype);
+ hdf_group_sobject->CreateOnDisk();
+ SaveAttributes(SO, hdf_group_sobject);
+ Impl_SaveObject(SO, hdf_group_sobject);
+ hdf_group_sobject->CloseOnDisk();
+ hdf_group_sobject =0; // will be deleted by father hdf object destructor
+ }
+ return true;
+}
+
+//============================================================================
+/*! Function : CanCopy
+ * Purpose :
+ */
+//============================================================================
+bool SALOMEDSImpl_Study::CanCopy(const SALOMEDSImpl_SObject& theObject,
+ SALOMEDSImpl_Driver* theEngine)
+{
+ _errorCode = "";
+ SALOMEDSImpl_SComponent aComponent = theObject.GetFatherComponent();
+ if (!aComponent) return false;
+ if (aComponent.GetLabel() == theObject.GetLabel()) return false;
+ std::string IOREngine;
+ if (!aComponent.ComponentIOR(IOREngine)) return false;
+ if (theEngine == NULL) return false;
+ return theEngine->CanCopy(theObject);
+}
+
+//============================================================================
+/*! Function : CopyLabel
+ * Purpose :
+ */
+//============================================================================
+bool SALOMEDSImpl_Study::CopyLabel(SALOMEDSImpl_Driver* theEngine,
+ const int theSourceStartDepth,
+ const DF_Label& theSource,
+ const DF_Label& theDestinationMain)
+{
+ _errorCode = "";
+
+ int a;
+ DF_Label aTargetLabel = theDestinationMain;
+ DF_Label aAuxTargetLabel = theDestinationMain.Father().FindChild(2);
+ for(a = theSource.Depth() - theSourceStartDepth; a > 0 ; a--) {
+ DF_Label aSourceLabel = theSource;
+ for(int aNbFather = 1; aNbFather < a; aNbFather++) aSourceLabel = aSourceLabel.Father();
+ aTargetLabel = aTargetLabel.FindChild(aSourceLabel.Tag());
+ aAuxTargetLabel = aAuxTargetLabel.FindChild(aSourceLabel.Tag());
+ }
+ // iterate attributes
+ std::vector<DF_Attribute*> attrList = theSource.GetAttributes();
+ for(int i = 0, len = attrList.size(); i<len; i++) {
+ DF_Attribute* anAttr = attrList[i];
+ std::string type = SALOMEDSImpl_GenericAttribute::Impl_GetType(anAttr);
+ if (type.substr(0, 17) == std::string("AttributeTreeNode")) continue; // never copy tree node attribute
+ if (type == std::string("AttributeTarget")) continue; // and target attribute
+
+ if (type == std::string("AttributeReference")) { // reference copied as Comment in aux tree
+ DF_Label aReferenced = dynamic_cast<SALOMEDSImpl_AttributeReference*>(anAttr)->Get();
+ std::string anEntry = aReferenced.Entry();
+ // store the value of name attribute of referenced label
+ SALOMEDSImpl_AttributeName* aNameAttribute;
+ if ((aNameAttribute=(SALOMEDSImpl_AttributeName*)aReferenced.FindAttribute(SALOMEDSImpl_AttributeName::GetID()))) {
+ anEntry += " ";
+ anEntry += aNameAttribute->Value();
+ }
+ SALOMEDSImpl_AttributeComment::Set(aAuxTargetLabel, anEntry);
+ continue;
+ }
+
+ if (type == std::string("AttributeIOR")) { // IOR => ID and TMPFile of Engine
+ std::string anEntry = theSource.Entry();
+ SALOMEDSImpl_SObject aSO = FindObjectID(anEntry);
+ int anObjID;
+ long aLen;
+ SALOMEDSImpl_TMPFile* aStream = theEngine->CopyFrom(aSO, anObjID, aLen);
+ std::string aResStr("");
+ for(a = 0; a < aLen; a++) {
+ aResStr += (char)(aStream->Get(a));
+ }
+
+ if(aStream) delete aStream;
+
+ SALOMEDSImpl_AttributeInteger::Set(aAuxTargetLabel, anObjID);
+ SALOMEDSImpl_AttributeName::Set(aAuxTargetLabel, aResStr);
+ continue;
+ }
+ DF_Attribute* aNewAttribute = anAttr->NewEmpty();
+ aTargetLabel.AddAttribute(aNewAttribute);
+ anAttr->Paste(aNewAttribute);
+ }
- if (aLocked) aProp->SetLocked(true);
+ return true;
+}
+
+//============================================================================
+/*! Function : Copy
+ * Purpose :
+ */
+//============================================================================
+bool SALOMEDSImpl_Study::Copy(const SALOMEDSImpl_SObject& theObject,
+ SALOMEDSImpl_Driver* theEngine)
+{
+ _errorCode = "";
+
+ // adoptation for alliances datamodel copy: without IOR attributes !!!
+ bool aStructureOnly; // copy only SObjects and attributes without component help
+ aStructureOnly = !theObject.GetLabel().IsAttribute(SALOMEDSImpl_AttributeIOR::GetID());
+
+ if (!_doc) {
+ _errorCode = "Document is null";
+ return false;
+ }
+
+ //Clear the clipboard
+ _clipboard->Main().Root().ForgetAllAttributes(true);
+ _appli->Close(_clipboard);
+ _clipboard = _appli->NewDocument("SALOME_STUDY");
+
+ // set component data type to the name attribute of root label
+ if (!aStructureOnly) {
+ SALOMEDSImpl_AttributeComment::Set(_clipboard->Main().Root(),
+ theEngine->ComponentDataType());
+ }
+ // iterate all theObject's label children
+ DF_Label aStartLabel = theObject.GetLabel();
+ int aSourceStartDepth = aStartLabel.Depth();
+
+ // copy main source label
+ CopyLabel(theEngine, aSourceStartDepth, aStartLabel, _clipboard->Main());
+
+ // copy all subchildren of the main source label (all levels)
+ DF_ChildIterator anIterator(aStartLabel, true);
+ for(; anIterator.More(); anIterator.Next()) {
+ CopyLabel(theEngine, aSourceStartDepth, anIterator.Value(), _clipboard->Main());
+ }
+
+ return true;
+}
+
+//============================================================================
+/*! Function : CanPaste
+ * Purpose :
+ */
+//============================================================================
+bool SALOMEDSImpl_Study::CanPaste(const SALOMEDSImpl_SObject& theObject,
+ SALOMEDSImpl_Driver* theEngine)
+{
+ _errorCode = "";
+
+ if (!_clipboard) {
+ _errorCode = "Clipboard is null";
+ return false;
+ }
+
+ SALOMEDSImpl_AttributeComment* aCompName = NULL;
+ if (!(aCompName=(SALOMEDSImpl_AttributeComment*)_clipboard->Main().Root().FindAttribute(SALOMEDSImpl_AttributeComment::GetID()))) {
+ _errorCode = "Clipboard has no component type";
+ return false;
+ }
+ SALOMEDSImpl_AttributeInteger* anObjID;
+ if (!(anObjID=(SALOMEDSImpl_AttributeInteger*)_clipboard->Main().Father().FindChild(2).FindAttribute(SALOMEDSImpl_AttributeInteger::GetID()))) {
+ _errorCode = "Clipboard has no object id";
+ return false;
+ }
+ SALOMEDSImpl_SComponent aComponent = theObject.GetFatherComponent();
+ if (!aComponent) {
+ _errorCode = "Object doesn't belong to component";
+ return false;
+ }
+
+ std::string IOREngine;
+ if (!aComponent.ComponentIOR(IOREngine)) {
+ _errorCode = "component has no IOR";
+ return false;
+ }
+ return theEngine->CanPaste(aCompName->Value(), anObjID->Value());
+}
+
+//============================================================================
+/*! Function : PasteLabel
+ * Purpose :
+ */
+//============================================================================
+DF_Label SALOMEDSImpl_Study::PasteLabel(SALOMEDSImpl_Driver* theEngine,
+ const DF_Label& theSource,
+ const DF_Label& theDestinationStart,
+ const bool isFirstElement)
+{
+ _errorCode = "";
+
+ // get corresponding source, target and auxiliary labels
+ DF_Label aTargetLabel = theDestinationStart;
+
+ DF_Label aAuxSourceLabel = theSource.Root().FindChild(2);
+ int a;
+ if (!isFirstElement) {
+ for(a = theSource.Depth() - 1; a > 0 ; a--) {
+ DF_Label aSourceLabel = theSource;
+ for(int aNbFather = 1; aNbFather < a; aNbFather++) aSourceLabel = aSourceLabel.Father();
+ aTargetLabel = aTargetLabel.FindChild(aSourceLabel.Tag());
+ aAuxSourceLabel = aAuxSourceLabel.FindChild(aSourceLabel.Tag());
+ }
+ SALOMEDSImpl_SObject so = GetSObject(aTargetLabel);
+ addSO_Notification(so);
+ }
+
+ // check auxiliary label for TMPFile => IOR
+ SALOMEDSImpl_AttributeName* aNameAttribute = NULL;
+ if ((aNameAttribute=(SALOMEDSImpl_AttributeName*)aAuxSourceLabel.FindAttribute(SALOMEDSImpl_AttributeName::GetID()))) {
+ SALOMEDSImpl_AttributeInteger* anObjID = (SALOMEDSImpl_AttributeInteger*)aAuxSourceLabel.FindAttribute(SALOMEDSImpl_AttributeInteger::GetID());
+ SALOMEDSImpl_AttributeComment* aComponentName = (SALOMEDSImpl_AttributeComment*)theSource.Root().FindAttribute(SALOMEDSImpl_AttributeComment::GetID());
+ std::string aCompName = aComponentName->Value();
+
+ if (theEngine->CanPaste(aCompName, anObjID->Value())) {
+ std::string aTMPStr = aNameAttribute->Value();
+ int aLen = aTMPStr.size();
+ unsigned char* aStream = NULL;
+ if(aLen > 0) {
+ aStream = new unsigned char[aLen+10];
+ for(a = 0; a < aLen; a++) {
+ aStream[a] = aTMPStr[a];
+ }
+ }
+
+ std::string anEntry = aTargetLabel.Entry();
+ SALOMEDSImpl_SObject aPastedSO = FindObjectID(anEntry);
+
+ if (isFirstElement) {
+ std::string aDestEntry = theEngine->PasteInto(aStream,
+ aLen,
+ anObjID->Value(),
+ aPastedSO.GetFatherComponent());
+ aTargetLabel = DF_Label::Label(theDestinationStart, aDestEntry);
+ } else
+ theEngine->PasteInto(aStream, aLen, anObjID->Value(), aPastedSO);
+
+ if(aStream != NULL) delete []aStream;
+ }
+ }
+
+ // iterate attributes
+ std::vector<DF_Attribute*> attrList = theSource.GetAttributes();
+ for(int i = 0, len = attrList.size(); i<len; i++) {
+ DF_Attribute* anAttr = attrList[i];
+ if (aTargetLabel.FindAttribute(anAttr->ID())) {
+ aTargetLabel.ForgetAttribute(anAttr->ID());
+ }
+ DF_Attribute* aNewAttribute = anAttr->NewEmpty();
+ aTargetLabel.AddAttribute(aNewAttribute);
+ anAttr->Paste(aNewAttribute);
+ }
+
+ // check auxiliary label for Comment => reference or name attribute of the referenced object
+ SALOMEDSImpl_AttributeComment* aCommentAttribute = NULL;
+ if ((aCommentAttribute=(SALOMEDSImpl_AttributeComment*)aAuxSourceLabel.FindAttribute(SALOMEDSImpl_AttributeComment::GetID()))) {
+ char * anEntry = new char[aCommentAttribute->Value().size() + 1];
+ strcpy(anEntry, std::string(aCommentAttribute->Value()).c_str());
+ char* aNameStart = strchr(anEntry, ' ');
+ if (aNameStart) {
+ *aNameStart = '\0';
+ aNameStart++;
+ }
+ // copy to the same study, reanimate reference
+ DF_Label aRefLabel = DF_Label::Label(aTargetLabel, anEntry);
+ SALOMEDSImpl_AttributeReference::Set(aTargetLabel, aRefLabel);
+ // target attributes structure support
+ SALOMEDSImpl_AttributeTarget::Set(aRefLabel)->Add(SALOMEDSImpl_Study::SObject(aTargetLabel));
+
+ delete [] anEntry;
+ }
+
+ return aTargetLabel;
+}
+
+//============================================================================
+/*! Function : Paste
+ * Purpose :
+ */
+//============================================================================
+SALOMEDSImpl_SObject SALOMEDSImpl_Study::Paste(const SALOMEDSImpl_SObject& theObject,
+ SALOMEDSImpl_Driver* theEngine)
+{
+ _errorCode = "";
+
+ SALOMEDSImpl_SObject so;
+
+ // if study is locked, then paste can't be done
+ if (GetProperties()->IsLocked()) {
+ _errorCode = "LockProtection";
+ throw LockProtection("LockProtection");
+ }
+
+ // if there is no component name, then paste only SObjects and attributes: without component help
+ SALOMEDSImpl_AttributeComment* aComponentName = NULL;
+ bool aStructureOnly = !(aComponentName=(SALOMEDSImpl_AttributeComment*)_clipboard->Main().Root().FindAttribute(SALOMEDSImpl_AttributeComment::GetID()));
+
+ // CAF document of current study usage
+ if (!_doc) {
+ _errorCode = "Document is null";
+ return so;
+ }
+
+ SALOMEDSImpl_SComponent aComponent = theObject.GetFatherComponent();
+
+ // fill root inserted SObject
+ DF_Label aStartLabel;
+ if (aStructureOnly) {
+ DF_Label anObjectLabel = DF_Label::Label(_doc->Main(), theObject.GetID());
+ aStartLabel = PasteLabel(theEngine, _clipboard->Main(), anObjectLabel, false);
+ } else {
+ DF_Label aComponentLabel = DF_Label::Label(_doc->Main(), aComponent.GetID());
+ aStartLabel = PasteLabel(theEngine, _clipboard->Main(), aComponentLabel, true);
+ }
+
+ // paste all sublebels
+ DF_ChildIterator anIterator(_clipboard->Main(), true);
+ for(; anIterator.More(); anIterator.Next()) {
+ PasteLabel(theEngine, anIterator.Value(), aStartLabel, false);
+ }
+
+ return SALOMEDSImpl_Study::SObject(aStartLabel);
+}
+
+//============================================================================
+/*! Function : GetPersistentReference
+ * Purpose : Get persistent reference of study (idem URL())
+ */
+//============================================================================
+std::string SALOMEDSImpl_Study::GetPersistentReference()
+{
+ _errorCode = "";
+ return URL();
}
//============================================================================
bool isRelative = false;
if(aLength == 0) { //Empty path - return the current context
- return GetSObject(_current);
+ return aSO;
}
if(aPath[0] != '/') //Relative path
SALOMEDSImpl_AttributeName* anAttr;
if(isRelative) {
- if(_current.IsNull()) return aSO;
- anIterator.Init(_current, false);
+ return aSO;
}
else {
if(aPath.size() == 1 && aPath[0] == '/') { //Root
return GetObjectPath(so);
}
-
-//============================================================================
-/*! Function : SetContext
- * Purpose : Sets the current context
- */
-//============================================================================
-bool SALOMEDSImpl_Study::SetContext(const std::string& thePath)
-{
- _errorCode = "";
- if(thePath.empty()) {
- _errorCode = "InvalidPath";
- return false;
- }
-
- std::string aPath(thePath), aContext("");
- bool isInvalid = false;
- SALOMEDSImpl_SObject aSO;
-
- if(aPath[0] != '/') { //Relative path
- aContext = GetContext();
- aContext += '/';
- aContext += aPath;
- }
- else
- aContext = aPath;
-
- try {
- aSO = FindObjectByPath(aContext);
- }
- catch( ... ) {
- isInvalid = true;
- }
-
- if(isInvalid || !aSO) {
- _errorCode = "InvalidContext";
- return false;
- }
-
- DF_Label aLabel = aSO.GetLabel();
- if(aLabel.IsNull()) {
- _errorCode = "InvalidContext";
- return false;
- }
- else
- _current = aLabel; //Set the current context
-
- return true;
-}
-
-//============================================================================
-/*! Function : GetContext
- * Purpose : Gets the current context
- */
-//============================================================================
-std::string SALOMEDSImpl_Study::GetContext()
-{
- _errorCode = "";
-
- if(_current.IsNull()) {
- _errorCode = "InvaidContext";
- return "";
- }
- SALOMEDSImpl_SObject so = GetSObject(_current);
- return GetObjectPath(so);
-}
-
-//============================================================================
-/*! Function : GetObjectNames
- * Purpose : method to get all object names in the given context (or in the current context, if 'theContext' is empty)
- */
-//============================================================================
-std::vector<std::string> SALOMEDSImpl_Study::GetObjectNames(const std::string& theContext)
-{
- _errorCode = "";
-
- std::vector<std::string> aResultSeq;
- DF_Label aLabel;
- if (theContext.empty()) {
- aLabel = _current;
- } else {
- DF_Label aTmp = _current;
- SetContext(theContext);
- aLabel = _current;
- _current = aTmp;
- }
- if (aLabel.IsNull()) {
- _errorCode = "InvalidContext";
- return aResultSeq;
- }
-
- DF_ChildIterator anIter (aLabel, true); // iterate all subchildren at all sublevels
- for (; anIter.More(); anIter.Next()) {
- DF_Label aLabel = anIter.Value();
- SALOMEDSImpl_AttributeName* aName;
- if ((aName=(SALOMEDSImpl_AttributeName*)aLabel.FindAttribute(SALOMEDSImpl_AttributeName::GetID())))
- aResultSeq.push_back(aName->Value());
- }
-
- return aResultSeq;
-}
-
-//============================================================================
-/*! Function : GetDirectoryNames
- * Purpose : method to get all directory names in the given context (or in the current context, if 'theContext' is empty)
- */
-//============================================================================
-std::vector<std::string> SALOMEDSImpl_Study::GetDirectoryNames(const std::string& theContext)
-{
- _errorCode = "";
-
- std::vector<std::string> aResultSeq;
- DF_Label aLabel;
- if (theContext.empty()) {
- aLabel = _current;
- } else {
- DF_Label aTmp = _current;
- SetContext(theContext);
- aLabel = _current;
- _current = aTmp;
- }
- if (aLabel.IsNull()) {
- _errorCode = "InvalidContext";
- return aResultSeq;
- }
-
- DF_ChildIterator anIter (aLabel, true); // iterate first-level children at all sublevels
- for (; anIter.More(); anIter.Next()) {
- DF_Label aLabel = anIter.Value();
- SALOMEDSImpl_AttributeLocalID* anID;
- if ((anID=(SALOMEDSImpl_AttributeLocalID*)aLabel.FindAttribute(SALOMEDSImpl_AttributeLocalID::GetID()))) {
- if (anID->Value() == DIRECTORYID) {
- SALOMEDSImpl_AttributeName* aName;
- if ((aName=(SALOMEDSImpl_AttributeName*)aLabel.FindAttribute(SALOMEDSImpl_AttributeName::GetID()))) {
- aResultSeq.push_back(aName->Value());
- }
- }
- }
- }
-
- return aResultSeq;
-}
-
-//============================================================================
-/*! Function : GetFileNames
- * Purpose : method to get all file names in the given context (or in the current context, if 'theContext' is empty)
- */
-//============================================================================
-std::vector<std::string> SALOMEDSImpl_Study::GetFileNames(const std::string& theContext)
-{
- _errorCode = "";
-
- std::vector<std::string> aResultSeq;
- DF_Label aLabel;
- if (theContext.empty()) {
- aLabel = _current;
- } else {
- DF_Label aTmp = _current;
- SetContext(theContext);
- aLabel = _current;
- _current = aTmp;
- }
- if (aLabel.IsNull()) {
- _errorCode = "InvalidContext";
- return aResultSeq;
- }
-
- DF_ChildIterator anIter (aLabel, true); // iterate all subchildren at all sublevels
- for (; anIter.More(); anIter.Next()) {
- DF_Label aLabel = anIter.Value();
- SALOMEDSImpl_AttributeLocalID* anID;
- if ((anID=(SALOMEDSImpl_AttributeLocalID*)aLabel.FindAttribute(SALOMEDSImpl_AttributeLocalID::GetID()))) {
- if (anID->Value() == FILELOCALID) {
- SALOMEDSImpl_AttributePersistentRef* aName;
- if ((aName=(SALOMEDSImpl_AttributePersistentRef*)aLabel.FindAttribute(SALOMEDSImpl_AttributePersistentRef::GetID()))) {
- std::string aFileName = aName->Value();
- if (aFileName.size() > 0)
- aResultSeq.push_back(aFileName.substr(strlen(FILEID), aFileName.size()));
- }
- }
- }
- }
-
- return aResultSeq;
-}
-
-//============================================================================
-/*! Function : GetComponentNames
- * Purpose : method to get all components names
- */
-//============================================================================
-std::vector<std::string> SALOMEDSImpl_Study::GetComponentNames(const std::string& theContext)
-{
- _errorCode = "";
-
- std::vector<std::string> aResultSeq;
- DF_ChildIterator anIter(_doc->Main(), false); // iterate all subchildren at first level
- for(; anIter.More(); anIter.Next()) {
- DF_Label aLabel = anIter.Value();
- SALOMEDSImpl_AttributeName* aName;
- if ((aName=(SALOMEDSImpl_AttributeName*)aLabel.FindAttribute(SALOMEDSImpl_AttributeName::GetID())))
- aResultSeq.push_back(aName->Value());
- }
-
- return aResultSeq;
-}
-
//============================================================================
/*! Function : NewChildIterator
* Purpose : Create a ChildIterator from an SObject
std::string SALOMEDSImpl_Study::Name()
{
_errorCode = "";
- return _name;
+ return Kernel_Utils::GetBaseName( _name, false );
}
//============================================================================
{
_errorCode = "";
_URL = url;
+ _name = url;
/*jfa: Now name of SALOMEDS study will correspond to name of SalomeApp study
std::string tmp(_URL);
adr = strtok(NULL, "/");
}
Name(aName);*/
- Name(url);
}
* Purpose :
*/
//============================================================================
-std::string SALOMEDSImpl_Study::_GetNoteBookAccess(const std::string& theStudyVar)
+std::string SALOMEDSImpl_Study::_GetNoteBookAccess()
{
std::string notebook = "import salome_notebook\n";
- notebook += _GetNoteBookAccessor() + " = salome_notebook.NoteBook(" + theStudyVar + ")" ;
+ notebook += _GetNoteBookAccessor() + " = salome_notebook.NoteBook()" ;
return notebook;
}
return GetProperties()->IsLocked();
}
-int SALOMEDSImpl_Study::StudyId()
-{
- _errorCode = "";
- return _StudyId;
-}
-
-void SALOMEDSImpl_Study::StudyId(int id)
-{
- _errorCode = "";
- _StudyId = id;
-}
-
void SALOMEDSImpl_Study::UpdateIORLabelMap(const std::string& anIOR,const std::string& anEntry)
{
_errorCode = "";
}
}
-SALOMEDSImpl_Study* SALOMEDSImpl_Study::GetStudy(const DF_Label& theLabel)
+SALOMEDSImpl_Study* SALOMEDSImpl_Study::GetStudyImpl(const DF_Label& theLabel)
{
SALOMEDSImpl_StudyHandle* Att;
if ((Att=(SALOMEDSImpl_StudyHandle*)theLabel.Root().FindAttribute(SALOMEDSImpl_StudyHandle::GetID()))) {
SALOMEDSImpl_SObject SALOMEDSImpl_Study::SObject(const DF_Label& theLabel)
{
- return GetStudy(theLabel)->GetSObject(theLabel);
+ return GetStudyImpl(theLabel)->GetSObject(theLabel);
}
SALOMEDSImpl_SComponent SALOMEDSImpl_Study::SComponent(const DF_Label& theLabel)
{
- return GetStudy(theLabel)->GetSComponent(theLabel);
+ return GetStudyImpl(theLabel)->GetSComponent(theLabel);
}
void SALOMEDSImpl_Study::IORUpdated(const SALOMEDSImpl_AttributeIOR* theAttribute)
{
std::string aString = theAttribute->Label().Entry();
- GetStudy(theAttribute->Label())->UpdateIORLabelMap(theAttribute->Value(), aString);
+ GetStudyImpl(theAttribute->Label())->UpdateIORLabelMap(theAttribute->Value(), aString);
}
std::vector<SALOMEDSImpl_SObject> SALOMEDSImpl_Study::FindDependances(const SALOMEDSImpl_SObject& anObject)
return _useCaseBuilder;
}
-
-//============================================================================
-/*! Function : Close
- * Purpose :
- */
-//============================================================================
-void SALOMEDSImpl_Study::Close()
-{
- _errorCode = "";
- _notifier = 0;
- _doc->GetApplication()->Close(_doc);
- _doc = NULL;
- _mapOfSO.clear();
- _mapOfSCO.clear();
-}
-
-
//============================================================================
/*! Function : GetSComponent
* Purpose :
sfp << "import sys" << std::endl;
sfp << "import " << aBatchModeScript << std::endl << std::endl;
- std::string aStudyVar = "salome.myStudy";
// initialization function
sfp << aBatchModeScript << ".salome_init()" << std::endl;
- if ( !isMultiFile ) {
- sfp << "theStudy = " << aStudyVar << std::endl << std::endl;
- aStudyVar = "theStudy";
- }
+
// notebook initialization
- sfp << _GetNoteBookAccess(aStudyVar) << std::endl;
+ sfp << _GetNoteBookAccess() << std::endl;
// extend sys.path with the directory where the script is being dumped to
- sfp << "sys.path.insert( 0, r\'" << thePath << "\')" << std::endl << std::endl;
+ sfp << "sys.path.insert(0, r\'" << thePath << "\')" << std::endl << std::endl;
// dump NoteBook variables
sfp << _GetStudyVariablesScript();
bool isValidScript;
long aStreamLength = 0;
- SALOMEDSImpl_TMPFile* aStream = aDriver->DumpPython(this, isPublished, isMultiFile, isValidScript, aStreamLength);
+ SALOMEDSImpl_TMPFile* aStream = aDriver->DumpPython(isPublished, isMultiFile, isValidScript, aStreamLength);
if ( !isValidScript )
isOk = false;
//Add to the main script a call to RebuildData of the generated by the component the Python script
sfp << "import " << aScriptName << std::endl;
- sfp << aScriptName << ".RebuildData(" << aBatchModeScript << ".myStudy)" << std::endl;
+ sfp << aScriptName << ".RebuildData()" << std::endl;
}
else
sfp << sfp2.str();
sfp << std::endl;
sfp << "if salome.sg.hasDesktop():" << std::endl;
- sfp << "\tsalome.sg.updateObjBrowser(True)" << std::endl;
+ sfp << "\tsalome.sg.updateObjBrowser()" << std::endl;
if(isDumpVisuals) { //Output the call to Session's method restoreVisualState
sfp << "\tiparameters.getSession().restoreVisualState(1)" << std::endl;
std::string SALOMEDSImpl_Study::GetDumpStudyComment(const char* theComponentName)
{
std::stringstream txt;
- txt << "# -*- coding: utf-8 -*-" << std::endl << std::endl;
+ txt << "#!/usr/bin/env python" << std::endl << std::endl;
txt << "###" << std::endl;
txt << "### This file is generated automatically by SALOME v"
<< KERNEL_VERSION_STR
if ( SALOMEDSImpl_AbstractCallback* goRegister = getGenObjRegister( label.GetDocument() ))
goRegister->UnRegisterGenObj( theIOR );
}
+
+//#######################################################################################################
+//# STATIC PRIVATE FUNCTIONS
+//#######################################################################################################
+
+//============================================================================
+/*! Function : SaveAttributes
+ * Purpose : Save attributes for object
+ */
+//============================================================================
+static void SaveAttributes(const SALOMEDSImpl_SObject& aSO, HDFgroup *hdf_group_sobject)
+{
+ hdf_size size[1];
+ std::vector<DF_Attribute*> attrList = aSO.GetLabel().GetAttributes();
+ DF_Attribute* anAttr = NULL;
+ for(int i = 0, len = attrList.size(); i<len; i++) {
+ anAttr = attrList[i];
+ //The following attributes are not supposed to be written to the file
+ std::string type = SALOMEDSImpl_GenericAttribute::Impl_GetType(anAttr);
+ if(type == std::string("AttributeIOR")) continue; //IOR attribute is not saved
+ std::string aSaveStr =anAttr->Save();
+ //cout << "Saving: " << aSO.GetID() << " type: "<< type<<"|" << endl;
+ size[0] = (hdf_int32) strlen(aSaveStr.c_str()) + 1;
+ HDFdataset *hdf_dataset = new HDFdataset((char*)type.c_str(), hdf_group_sobject, HDF_STRING,size, 1);
+ hdf_dataset->CreateOnDisk();
+ hdf_dataset->WriteOnDisk((char*)aSaveStr.c_str());
+ hdf_dataset->CloseOnDisk();
+ hdf_dataset=0; //will be deleted by hdf_sco_group destructor
+ }
+}
+
+//===========================================================================
+//Function : ReadAttributes
+//===========================================================================
+static void ReadAttributes(SALOMEDSImpl_Study* theStudy,
+ const SALOMEDSImpl_SObject& aSO,
+ HDFdataset* hdf_dataset)
+{
+ hdf_dataset->OpenOnDisk();
+
+ DF_Attribute* anAttr = NULL;
+ char* current_string = new char[hdf_dataset->GetSize()+1];
+ hdf_dataset->ReadFromDisk(current_string);
+ //cout << "Reading attr type = " << hdf_dataset->GetName() << " SO = " << aSO.GetID() << endl;
+ if (!strcmp(hdf_dataset->GetName(),"COMPONENTDATATYPE")) {
+ anAttr = theStudy->NewBuilder()->FindOrCreateAttribute(aSO, "AttributeComment");
+ }
+ else if (!strcmp(hdf_dataset->GetName(),"AttributeReference") ||
+ !strcmp(hdf_dataset->GetName(),"Reference")) { // Old format maintainance
+ theStudy->NewBuilder()->Addreference(aSO, theStudy->CreateObjectID(current_string));
+ delete [] (current_string);
+ hdf_dataset->CloseOnDisk();
+ return;
+ }
+ else {
+ anAttr = theStudy->NewBuilder()->FindOrCreateAttribute(aSO, hdf_dataset->GetName());
+ }
+
+ if (anAttr) {
+ anAttr->Load(current_string);
+ }
+
+ delete [] (current_string);
+ hdf_dataset->CloseOnDisk();
+}
+
+//============================================================================
+//Function : BuildlTree
+//============================================================================
+static void BuildTree (SALOMEDSImpl_Study* theStudy, HDFgroup* hdf_current_group)
+{
+ hdf_current_group->OpenOnDisk();
+ SALOMEDSImpl_SObject aSO;
+ char* Entry = hdf_current_group->GetName();
+ if (strcmp(Entry,"STUDY_STRUCTURE") == 0) {
+ aSO = theStudy->CreateObjectID("0:1");
+ }
+ else {
+ aSO = theStudy->CreateObjectID(Entry);
+ }
+
+ char name[HDF_NAME_MAX_LEN+1];
+ int nbsons = hdf_current_group->nInternalObjects();
+ for (int i=0; i<nbsons; i++) {
+ hdf_current_group->InternalObjectIndentify(i,name);
+ if (strncmp(name, "INTERNAL_COMPLEX",16) == 0) continue;
+ hdf_object_type type = hdf_current_group->InternalObjectType(name);
+
+ if (type == HDF_DATASET) {
+ HDFdataset* new_dataset = new HDFdataset(name,hdf_current_group);
+ ReadAttributes(theStudy,aSO,new_dataset);
+ new_dataset = 0; // will be deleted by father destructor
+ }
+ else if (type == HDF_GROUP) {
+ HDFgroup* new_group = new HDFgroup(name,hdf_current_group);
+ BuildTree (theStudy, new_group);
+ new_group = 0; // will be deleted by father destructor
+ }
+ }
+ hdf_current_group->CloseOnDisk();
+}
+
+
+//============================================================================
+//Function : Translate_IOR_to_persistentID
+//============================================================================
+static void Translate_IOR_to_persistentID (const SALOMEDSImpl_SObject& so,
+ SALOMEDSImpl_Driver* engine,
+ bool isMultiFile,
+ bool isASCII)
+{
+ DF_ChildIterator itchild(so.GetLabel());
+ std::string ior_string, persistent_string, curid;
+
+ for (; itchild.More(); itchild.Next()) {
+ SALOMEDSImpl_SObject current = SALOMEDSImpl_Study::SObject(itchild.Value());
+ SALOMEDSImpl_AttributeIOR* IOR = NULL;
+ if ((IOR=(SALOMEDSImpl_AttributeIOR*)current.GetLabel().FindAttribute(SALOMEDSImpl_AttributeIOR::GetID()))) {
+ ior_string = IOR->Value();
+
+ persistent_string = engine->IORToLocalPersistentID (current, ior_string, isMultiFile, isASCII);
+ SALOMEDSImpl_AttributePersistentRef::Set(current.GetLabel(), persistent_string);
+ }
+ Translate_IOR_to_persistentID (current, engine, isMultiFile, isASCII);
+ }
+}
+
+void ReadNoteBookVariables(SALOMEDSImpl_Study* theStudy, HDFgroup* theGroup)
+{
+ if(!theGroup)
+ return;
+
+ HDFgroup* new_group =0;
+ HDFdataset* new_dataset =0;
+
+ char aVarName[HDF_NAME_MAX_LEN+1];
+ char *currentVarType = 0;
+ char *currentVarValue = 0;
+ char *currentVarIndex = 0;
+ int order = 0;
+ //Open HDF group with notebook variables
+ theGroup->OpenOnDisk();
+
+ //Get Nb of variables
+ int aNbVars = theGroup->nInternalObjects();
+
+ std::map<int,SALOMEDSImpl_GenericVariable*> aVarsMap;
+
+ for( int iVar=0;iVar < aNbVars;iVar++ ) {
+ theGroup->InternalObjectIndentify(iVar,aVarName);
+ hdf_object_type type = theGroup->InternalObjectType(aVarName);
+ if(type == HDF_GROUP) {
+
+ //Read Variable
+ new_group = new HDFgroup(aVarName,theGroup);
+ new_group->OpenOnDisk();
+
+ //Read Type
+ new_dataset = new HDFdataset("VARIABLE_TYPE",new_group);
+ new_dataset->OpenOnDisk();
+ currentVarType = new char[new_dataset->GetSize()+1];
+ new_dataset->ReadFromDisk(currentVarType);
+ new_dataset->CloseOnDisk();
+ new_dataset = 0; //will be deleted by hdf_sco_group destructor
+
+ //Read Order
+ if(new_group->ExistInternalObject("VARIABLE_INDEX")) {
+ new_dataset = new HDFdataset("VARIABLE_INDEX",new_group);
+ new_dataset->OpenOnDisk();
+ currentVarIndex = new char[new_dataset->GetSize()+1];
+ new_dataset->ReadFromDisk(currentVarIndex);
+ new_dataset->CloseOnDisk();
+ new_dataset = 0; //will be deleted by hdf_sco_group destructor
+ order = atoi(currentVarIndex);
+ delete [] currentVarIndex;
+ }
+ else
+ order = iVar;
+
+ //Read Value
+ new_dataset = new HDFdataset("VARIABLE_VALUE",new_group);
+ new_dataset->OpenOnDisk();
+ currentVarValue = new char[new_dataset->GetSize()+1];
+ new_dataset->ReadFromDisk(currentVarValue);
+ new_dataset->CloseOnDisk();
+ new_dataset = 0; //will be deleted by hdf_sco_group destructor
+
+ new_group->CloseOnDisk();
+ new_group = 0; //will be deleted by hdf_sco_group destructor
+
+ SALOMEDSImpl_GenericVariable::VariableTypes aVarType =
+ SALOMEDSImpl_GenericVariable::String2VariableType(std::string(currentVarType));
+ delete [] currentVarType;
+
+ //Create variable and add it in the study
+ SALOMEDSImpl_GenericVariable* aVariable =
+ new SALOMEDSImpl_ScalarVariable(aVarType,std::string(aVarName));
+ aVariable->Load(std::string(currentVarValue));
+ aVarsMap.insert(std::make_pair(order,aVariable));
+ delete [] currentVarValue;
+ }
+ }
+
+ std::map<int,SALOMEDSImpl_GenericVariable*>::const_iterator it= aVarsMap.begin();
+ for(;it!=aVarsMap.end();it++)
+ theStudy->AddVariable((*it).second);
+
+ theGroup->CloseOnDisk();
+}
+
#include "SALOMEDSImpl_ChildIterator.hxx"
#include "SALOMEDSImpl_GenericVariable.hxx"
-class SALOMEDSImpl_StudyManager;
+class HDFgroup;
class SALOMEDSImpl_GenericAttribute;
{
private:
std::string _name;
+ DF_Application* _appli;
DF_Document* _doc; // Document
+ DF_Document* _clipboard;
bool _Saved; // True if the Study is saved
std::string _URL; //URL of the persistent reference of the study
- int _StudyId;
- DF_Label _current;
bool _autoFill;
std::string _errorCode;
std::vector<std::string> _lockers;
std::string _GetStudyVariablesScript();
std::string _GetNoteBookAccessor();
- std::string _GetNoteBookAccess(const std::string& theStudyVar);
+ std::string _GetNoteBookAccess();
public:
- static SALOMEDSImpl_Study* GetStudy(const DF_Label& theLabel);
+ static SALOMEDSImpl_Study* GetStudyImpl(const DF_Label& theLabel);
static SALOMEDSImpl_SObject SObject(const DF_Label& theLabel);
static SALOMEDSImpl_SComponent SComponent(const DF_Label& theLabel);
static void IORUpdated(const SALOMEDSImpl_AttributeIOR* theAttribute);
//! standard constructor
- SALOMEDSImpl_Study(const DF_Document*, const std::string& study_name);
+ SALOMEDSImpl_Study();
//! standard destructor
virtual ~SALOMEDSImpl_Study();
- //! method to Get persistent reference of study (idem URL())
- virtual std::string GetPersistentReference();
+ virtual void Init();
+ virtual void Clear();
+
+ //! method to Open a Study from it's persistent reference
+ virtual bool Open(const std::string& aStudyUrl);
+
+ //! method to save a Study
+ virtual bool Save(SALOMEDSImpl_DriverFactory* aFactory,
+ bool theMultiFile,
+ bool theASCII);
+
+ //! method to save a Study to the persistent reference aUrl
+ virtual bool SaveAs(const std::string& aUrl,
+ SALOMEDSImpl_DriverFactory* aFactory,
+ bool theMultiFile,
+ bool theASCII);
+
+ bool CopyLabel(SALOMEDSImpl_Driver* theEngine,
+ const int theSourceStartDepth,
+ const DF_Label& theSource,
+ const DF_Label& theDestinationMain);
- //! method to Get transient reference of study
- virtual std::string GetTransientReference();
+ DF_Label PasteLabel(SALOMEDSImpl_Driver* theEngine,
+ const DF_Label& theSource,
+ const DF_Label& theDestinationStart,
+ const bool isFirstElement);
- virtual void SetTransientReference(const std::string& theIOR);
+ virtual bool CanCopy(const SALOMEDSImpl_SObject& theObject, SALOMEDSImpl_Driver* Engine);
+ virtual bool Copy(const SALOMEDSImpl_SObject& theObject, SALOMEDSImpl_Driver* Engine);
+ virtual bool CanPaste(const SALOMEDSImpl_SObject& theObject, SALOMEDSImpl_Driver* Engine);
+ virtual SALOMEDSImpl_SObject Paste(const SALOMEDSImpl_SObject& theObject, SALOMEDSImpl_Driver* Engine);
+
+ // _SaveAs private function called by Save and SaveAs
+ virtual bool Impl_SaveAs(const std::string& aUrl,
+ SALOMEDSImpl_DriverFactory* aFactory,
+ bool theMultiFile,
+ bool theASCII);
+
+ // _SaveObject private function called by _SaveAs
+ virtual bool Impl_SaveObject(const SALOMEDSImpl_SObject& SC, HDFgroup *hdf_group_datatype);
+
+ virtual bool Impl_SaveProperties(HDFgroup *hdf_group);
+
+
+ //! method to Get persistent reference of study (idem URL())
+ virtual std::string GetPersistentReference();
//! method to detect if a study is empty
virtual bool IsEmpty();
std::string GetObjectPathByIOR(const std::string& theIOR);
- //! method to set a context: root ('/') is UserData component
- virtual bool SetContext(const std::string& thePath);
-
- //! method to get a context
- virtual std::string GetContext();
-
- //! method to get all object names in the given context (or in the current context, if 'theContext' is empty)
- virtual std::vector<std::string> GetObjectNames(const std::string& theContext);
-
- //! method to get all directory names in the given context (or in the current context, if 'theContext' is empty)
- virtual std::vector<std::string> GetDirectoryNames(const std::string& theContext);
-
- //! method to get all file names in the given context (or in the current context, if 'theContext' is empty)
- virtual std::vector<std::string> GetFileNames(const std::string& theContext);
-
- //! method to get all components names
- virtual std::vector<std::string> GetComponentNames(const std::string& theContext);
-
//! method to Create a ChildIterator from an SObject
virtual SALOMEDSImpl_ChildIterator NewChildIterator(const SALOMEDSImpl_SObject& aSO);
virtual bool IsLocked();
- virtual int StudyId();
-
- virtual void StudyId(int id);
-
virtual void DeleteIORLabelMapItem(const std::string& anIOR);
virtual void UpdateIORLabelMap(const std::string& anIOR, const std::string& aLabel);
virtual SALOMEDSImpl_UseCaseBuilder* GetUseCaseBuilder();
- virtual void Close();
-
void EnableUseCaseAutoFilling(bool isEnabled);
virtual std::string GetErrorCode() { return _errorCode; }
virtual DF_Attribute* GetAttribute(const std::string& theEntry,
const std::string& theType);
- virtual bool HasCurrentContext() { return !_current.IsNull(); }
-
virtual bool DumpStudy(const std::string& thePath,
const std::string& theBaseName,
bool isPublished,
static void UnRegisterGenObj(const std::string& theIOR, DF_Label label);
void setGenObjRegister(SALOMEDSImpl_AbstractCallback* theRegister);
- friend class SALOMEDSImpl_StudyManager;
friend class SALOMEDSImpl_GenericAttribute;
friend class SALOMEDSImpl_GenericVariable;
};
//============================================================================
SALOMEDSImpl_StudyBuilder::SALOMEDSImpl_StudyBuilder(const SALOMEDSImpl_Study* theOwner)
{
- _errorCode = "";
+ _errorCode = "";
_callbackOnAdd=NULL;
_callbackOnRemove = NULL;
- _study = (SALOMEDSImpl_Study*)theOwner;
- _doc = _study->GetDocument();
+ _study = (SALOMEDSImpl_Study*)theOwner;
+ _doc = _study->GetDocument();
}
//============================================================================
return true;
}
-
-
-//============================================================================
-/*! Function : AddDirectory
- * Purpose : adds a new directory with a path = thePath
- */
-//============================================================================
-bool SALOMEDSImpl_StudyBuilder::AddDirectory(const std::string& thePath)
-{
- _errorCode = "";
- CheckLocked();
- if(thePath.empty()) {
- _errorCode = "Invalid path";
- return false;
- }
-
- std::string aPath(thePath), aContext(""), aFatherPath;
- DF_Label aLabel;
- SALOMEDSImpl_SObject anObject;
-
- try {
- anObject = _study->FindObjectByPath(thePath); //Check if the directory already exists
- }
- catch(...) { }
-
- if(anObject) {
- _errorCode = "StudyNameAlreadyUsed";
- return false;
- }
-
- if(aPath[0] != '/') { //Relative path
- aPath.insert(aPath.begin(), '/');
- aPath = _study->GetContext() + aPath;
- }
-
- std::vector<std::string> vs = SALOMEDSImpl_Tool::splitString(aPath, '/');
- if(vs.size() == 1)
- aFatherPath = "/";
- else {
- for(int i = 0, len = vs.size()-1; i<len; i++) {
- aFatherPath += "/";
- aFatherPath += vs[i];
- }
- }
-
- try {
- anObject = _study->FindObjectByPath(aFatherPath); //Check if the father directory exists
- }
- catch(...) { ; }
- if(!anObject) {
- _errorCode = "StudyInvalidDirectory";
- return false;
- }
-
- SALOMEDSImpl_SObject aNewObject = NewObject(anObject);
- aLabel = aNewObject.GetLabel();
- if(aLabel.IsNull()) {
- _errorCode = "StudyInvalidComponent";
- return false;
- }
-
- SALOMEDSImpl_AttributeName::Set(aLabel, vs.back());
-
- //Set LocalID attribute to identify the directory object
- SALOMEDSImpl_AttributeLocalID::Set(aLabel, DIRECTORYID);
-
- _doc->SetModified(true);
-
- return true;
-}
-
-
//============================================================================
/*! Function : SetGUID
* Purpose :
virtual SALOMEDSImpl_SObject NewObjectToTag(const SALOMEDSImpl_SObject& theFatherObject,
const int theTag);
- //! The methods adds a new subdirectory, the path can be absolute or relative (then the current context is used)
- virtual bool AddDirectory(const std::string& thePath);
-
virtual bool LoadWith(const SALOMEDSImpl_SComponent& sco, SALOMEDSImpl_Driver* Engine);
virtual bool Load(const SALOMEDSImpl_SObject& sco);
+++ /dev/null
-// 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 : SALOMEDSImpl_StudyManager.cxx
-// Author : Sergey RUIN
-// Module : SALOME
-//
-#include "SALOMEDSImpl_StudyManager.hxx"
-
-#include "DF_ChildIterator.hxx"
-#include "HDFexplorer.hxx"
-#include "Basics_Utils.hxx"
-
-//Warning undef of Ascii Winwows define
-#ifdef WIN32
-# undef GetUserName
-#endif
-
-#include "SALOMEDSImpl_Attributes.hxx"
-#include "SALOMEDSImpl_Tool.hxx"
-#include "SALOMEDSImpl_SComponent.hxx"
-#include "SALOMEDSImpl_GenericAttribute.hxx"
-#include "SALOMEDSImpl_ScalarVariable.hxx"
-#include "SALOMEDSImpl_IParameters.hxx"
-#include <map>
-
-#include "HDFOI.hxx"
-#include <iostream>
-#include <stdlib.h>
-#include <string.h>
-
-#define USE_CASE_LABEL_ID "0:2"
-
-static void SaveAttributes(const SALOMEDSImpl_SObject& SO, HDFgroup *hdf_group_sobject);
-static void ReadAttributes(SALOMEDSImpl_Study*, const SALOMEDSImpl_SObject&, HDFdataset* );
-static void BuildTree (SALOMEDSImpl_Study*, HDFgroup*);
-static void Translate_IOR_to_persistentID (const SALOMEDSImpl_SObject&,
- SALOMEDSImpl_Driver*, bool isMultiFile, bool isASCII);
-static void ReadNoteBookVariables(SALOMEDSImpl_Study* theStudy, HDFgroup* theGroup);
-
-namespace {
- class StudyUnlocker
- {
- public:
- StudyUnlocker( SALOMEDSImpl_Study* study ): myStudy( study ), myLocked( false )
- {
- myPrevLocked = myStudy->GetProperties()->IsLocked();
- resume();
- }
- ~StudyUnlocker()
- {
- suspend();
- }
- void suspend()
- {
- if (myLocked) {
- myStudy->GetProperties()->SetLocked(true);
- myPrevLocked = myLocked;
- myLocked = false;
- }
- }
- void resume()
- {
- if (myPrevLocked) {
- myStudy->GetProperties()->SetLocked(false);
- myLocked = myPrevLocked;
- myPrevLocked = false;
- }
- }
- private:
- SALOMEDSImpl_Study* myStudy;
- bool myLocked;
- bool myPrevLocked;
- };
-}
-
-//============================================================================
-/*! Function : SALOMEDSImpl_StudyManager
- * Purpose : SALOMEDSImpl_StudyManager constructor
- */
-//============================================================================
-SALOMEDSImpl_StudyManager::SALOMEDSImpl_StudyManager()
-{
- _errorCode = "";
- _appli = new DF_Application();
- _IDcounter = 0;
- _clipboard = _appli->NewDocument("SALOME_STUDY");
-}
-
-//============================================================================
-/*! Function : ~SALOMEDSImpl_StudyManager
- * Purpose : SALOMEDSImpl_StudyManager destructor
- */
-//============================================================================
-SALOMEDSImpl_StudyManager::~SALOMEDSImpl_StudyManager()
-{
- _appli->Close(_clipboard);
- // Destroy application
- delete _appli;
-}
-
-
-//============================================================================
-/*! Function : NewStudy
- * Purpose : Create a New Study of name study_name
- */
-//==================================================T==========================
-SALOMEDSImpl_Study* SALOMEDSImpl_StudyManager::NewStudy(const std::string& study_name)
-{
- _errorCode = "";
-
- DF_Document* Doc = _appli->NewDocument("SALOME_STUDY");
-
- SALOMEDSImpl_Study* Study = new SALOMEDSImpl_Study(Doc, study_name);
-
- _IDcounter++;
- Study->StudyId( _IDcounter );
-
- // set Study properties
- SALOMEDSImpl_AttributeStudyProperties* aProp = Study->GetProperties();
-
- int month=0,day=0,year=0,hh=0,mn=0,ss=0;
- SALOMEDSImpl_Tool::GetSystemDate(year, month, day, hh, mn, ss);
- aProp->SetModification(SALOMEDSImpl_Tool::GetUserName(),
- mn, hh, day, month, year);
- aProp->SetCreationMode(1); //"from scratch"
-
- return Study;
-}
-
-//============================================================================
-/*! Function : Open
- * Purpose : Open a Study from it's persistent reference
- */
-//============================================================================
-SALOMEDSImpl_Study* SALOMEDSImpl_StudyManager::Open(const std::string& aUrl)
-{
- // Set "C" locale temporarily to avoid possible localization problems
- Kernel_Utils::Localizer loc;
-
- _errorCode = "";
-
- // open the HDFFile
- HDFfile *hdf_file =0;
- HDFgroup *hdf_group_study_structure =0;
- HDFgroup *hdf_notebook_vars = 0;
-
- char* aC_HDFUrl;
- std::string aHDFUrl;
- bool isASCII = false;
- if (HDFascii::isASCII(aUrl.c_str())) {
- isASCII = true;
- char* aResultPath = HDFascii::ConvertFromASCIIToHDF(aUrl.c_str());
- if ( !aResultPath )
- return NULL;
- aC_HDFUrl = new char[strlen(aResultPath) + 19];
- sprintf(aC_HDFUrl, "%shdf_from_ascii.hdf", aResultPath);
- delete [] (aResultPath);
- aHDFUrl = aC_HDFUrl;
- delete [] aC_HDFUrl;
- } else {
- aHDFUrl = aUrl;
- }
-
-
- hdf_file = new HDFfile((char*)aHDFUrl.c_str());
- try {
- hdf_file->OpenOnDisk(HDF_RDONLY);// mpv: was RDWR, but opened file can be write-protected too
- }
- catch (HDFexception)
- {
- char *eStr;
- eStr = new char[strlen(aUrl.c_str())+17];
- sprintf(eStr,"Can't open file %s",aUrl.c_str());
- delete [] eStr;
- _errorCode = std::string(eStr);
- return NULL;
- }
-
- // Temporary aStudyUrl in place of study name
- DF_Document* Doc = _appli->NewDocument("SALOME_STUDY");
-
- SALOMEDSImpl_Study* Study = new SALOMEDSImpl_Study(Doc, aUrl);
-
- _IDcounter++;
- Study->StudyId( _IDcounter );
-
- // Assign the value of the URL in the study object
- Study->URL (aUrl);
-
- SALOMEDSImpl_AttributePersistentRef::Set(Doc->Main(), aUrl);
-
- if (!hdf_file->ExistInternalObject("STUDY_STRUCTURE")) {
- _errorCode = "Study is empty";
- return Study;
- }
-
- //Create the Structure of the Document
- hdf_group_study_structure = new HDFgroup("STUDY_STRUCTURE",hdf_file);
-
- try {
- BuildTree (Study, hdf_group_study_structure);
- }
- catch (HDFexception)
- {
- char *eStr = new char [strlen(aUrl.c_str())+17];
- sprintf(eStr,"Can't open file %s", aUrl.c_str());
- _errorCode = std::string(eStr);
- return NULL;
- }
-
- //Read and create notebook variables
- if(hdf_file->ExistInternalObject("NOTEBOOK_VARIABLES")) {
- hdf_notebook_vars = new HDFgroup("NOTEBOOK_VARIABLES",hdf_file);
- ReadNoteBookVariables(Study,hdf_notebook_vars);
- hdf_notebook_vars =0; //will be deleted by hdf_sco_group destructor
- }
-
- hdf_file->CloseOnDisk();
- hdf_group_study_structure = new HDFgroup("STUDY_STRUCTURE",hdf_file);
-
- if (isASCII) {
- std::vector<std::string> aFilesToRemove;
- aFilesToRemove.push_back("hdf_from_ascii.hdf");
- SALOMEDSImpl_Tool::RemoveTemporaryFiles(SALOMEDSImpl_Tool::GetDirFromPath(aHDFUrl), aFilesToRemove, true);
- }
-
- delete hdf_file; // all related hdf objects will be deleted
-
- // unlock study if it is locked, to set components versions
- StudyUnlocker unlock(Study);
-
- //For old studies we have to add "unknown" version tag for all stored components
- SALOMEDSImpl_SComponentIterator itcomponent = Study->NewComponentIterator();
- for (; itcomponent.More(); itcomponent.Next())
- {
- SALOMEDSImpl_SComponent sco = itcomponent.Value();
- std::string aCompType = sco.GetComment();
- if ( aCompType == SALOMEDSImpl_IParameters::getDefaultVisualComponent() ) continue;
- if ( Study->GetProperties()->GetComponentVersions( aCompType ).empty() )
- Study->GetProperties()->SetComponentVersion( aCompType, "" ); // empty version means "unknown"
- }
-
- return Study;
-}
-
-
-
-//============================================================================
-/*! Function : Close
- * Purpose : Close a study.
- * If the study hasn't been saved, ask the user to confirm the
- * close action without saving
- */
-
-//============================================================================
-void SALOMEDSImpl_StudyManager::Close(SALOMEDSImpl_Study* aStudy)
-{
- _errorCode = "";
-
- if(!aStudy) {
- _errorCode = "Study is null";
- return;
- }
-
- aStudy->Close();
- DF_Document* doc=aStudy->GetDocument();
- _appli->Close(doc);
-}
-
-//============================================================================
-/*! Function : Save
- * Purpose : Save a Study to it's persistent reference
- */
-//============================================================================
-bool SALOMEDSImpl_StudyManager::Save(SALOMEDSImpl_Study* aStudy,
- SALOMEDSImpl_DriverFactory* aFactory,
- bool theMultiFile)
-{
- _errorCode = "";
-
- std::string url = aStudy->URL();
- if (url.empty()) {
- _errorCode = "No path specified to save the study. Nothing done";
- return false;
- }
- else {
- return Impl_SaveAs(url,aStudy, aFactory, theMultiFile, false);
- }
-
- return false;
-}
-
-bool SALOMEDSImpl_StudyManager::SaveASCII(SALOMEDSImpl_Study* aStudy,
- SALOMEDSImpl_DriverFactory* aFactory,
- bool theMultiFile)
-{
- _errorCode = "";
-
- std::string url = aStudy->URL();
- if (url.empty()) {
- _errorCode = "No path specified to save the study. Nothing done";
- return false;
- }
- else {
- return Impl_SaveAs(url,aStudy, aFactory, theMultiFile, true);
- }
-
- return false;
-}
-
-//=============================================================================
-/*! Function : SaveAs
- * Purpose : Save a study to the persistent reference aUrl
- */
-//============================================================================
-bool SALOMEDSImpl_StudyManager::SaveAs(const std::string& aUrl,
- SALOMEDSImpl_Study* aStudy,
- SALOMEDSImpl_DriverFactory* aFactory,
- bool theMultiFile)
-{
- _errorCode = "";
- return Impl_SaveAs(aUrl,aStudy, aFactory, theMultiFile, false);
-}
-
-bool SALOMEDSImpl_StudyManager::SaveAsASCII(const std::string& aUrl,
- SALOMEDSImpl_Study* aStudy,
- SALOMEDSImpl_DriverFactory* aFactory,
- bool theMultiFile)
-{
- _errorCode = "";
- return Impl_SaveAs(aUrl,aStudy, aFactory, theMultiFile, true);
-}
-
-//============================================================================
-/*! Function : GetOpenStudies
- * Purpose : Get name list of open studies in the session
- */
-//============================================================================
-std::vector<SALOMEDSImpl_Study*> SALOMEDSImpl_StudyManager::GetOpenStudies()
-{
- _errorCode = "";
- std::vector<SALOMEDSImpl_Study*> aList;
-
- int nbDocs = _appli->NbDocuments();
-
- if(nbDocs == 0) {
- _errorCode = "No active study in this session";
- return aList;
- }
- else {
- SALOMEDSImpl_Study* aStudy;
- std::vector<int> ids = _appli->GetDocumentIDs();
- for (int i = 0, len = ids.size(); i<len; i++) {
- DF_Document* D = _appli->GetDocument(ids[i]);
- if(D == _clipboard) continue;
- aStudy = SALOMEDSImpl_Study::GetStudy(D->Main());
- if(!aStudy) continue;
- aList.push_back(aStudy);
- }
- }
-
- return aList;
-}
-
-//============================================================================
-/*! Function : GetStudyByName
- * Purpose : Get a study from its name
- */
-//============================================================================
-SALOMEDSImpl_Study* SALOMEDSImpl_StudyManager::GetStudyByName
- (const std::string& aStudyName)
-{
- _errorCode = "";
- int nbDocs = _appli->NbDocuments();
-
- if (nbDocs == 0) {
- _errorCode = "No active study in this session";
- return NULL;
- }
- else {
- std::vector<SALOMEDSImpl_Study*> studies = GetOpenStudies();
- for (int i = 0, len = studies.size(); i<len; i++) {
- if (studies[i]->Name() == aStudyName) return studies[i];
- }
- }
-
- _errorCode = std::string("Found no study with the name ") + aStudyName;
- return NULL;
-}
-
-//============================================================================
-/*! Function : GetStudyByID
- * Purpose : Get a study from its ID
- */
-//============================================================================
-SALOMEDSImpl_Study* SALOMEDSImpl_StudyManager::GetStudyByID(int aStudyID)
-{
- _errorCode = "";
- int nbDocs = _appli->NbDocuments();
-
- if (nbDocs == 0) {
- _errorCode = "No active study in this session";
- return NULL;
- }
- else {
- std::vector<SALOMEDSImpl_Study*> studies = GetOpenStudies();
- for (int i = 0, len = studies.size(); i<len; i++) {
- if (studies[i]->StudyId() == aStudyID) return studies[i];
- }
- }
-
- _errorCode = "Found no study with the given ID";
- return NULL;
-}
-
-//=============================================================================
-/*! Function : _SaveProperties
- * Purpose : save the study properties in HDF file
- */
-//============================================================================
-bool SALOMEDSImpl_StudyManager::Impl_SaveProperties(SALOMEDSImpl_Study* aStudy,
- HDFgroup *hdf_group)
-{
- _errorCode = "";
-
- HDFdataset *hdf_dataset = 0;
- hdf_size size[1];
- hdf_int32 name_len;
-
- // add modifications list (user and date of save)
- SALOMEDSImpl_AttributeStudyProperties* aProp = aStudy->GetProperties();
-
- // unlock study if it is locked, to set modification date
- StudyUnlocker unlock(aStudy);
-
- int month=0,day=0,year=0,hh=0,mn=0,ss=0;
- SALOMEDSImpl_Tool::GetSystemDate(year, month, day, hh, mn, ss);
- aProp->SetModification(SALOMEDSImpl_Tool::GetUserName(),
- mn, hh, day, month, year);
-
- // lock study back if it was locked initially, to write correct value of Locked flag
- unlock.suspend();
-
- std::vector<std::string> aNames;
- std::vector<int> aMinutes, aHours, aDays, aMonths, aYears;
-
- aProp->GetModifications(aNames, aMinutes, aHours, aDays, aMonths, aYears);
-
- std::string units = aProp->GetUnits();
- std::string comment = aProp->GetComment();
-
- std::map< std::string, std::vector<std::string> > allVersions = aProp->GetComponentsVersions();
- std::map<std::string, std::string> versions;
-
- int aLength = 0, aLength1 = 0, anIndex, i, unitsSize = 0, commentSize = 0;
-
- for(i=1; i<=aNames.size(); i++)
- aLength += aNames[i-1].size() + 1;
-
- std::map< std::string, std::vector<std::string> >::const_iterator it;
- for (it = allVersions.begin(); it != allVersions.end(); ++it ) {
- std::string vlist = "";
- std::vector<std::string> vl = it->second;
- std::vector<std::string>::const_iterator vlit;
- for ( vlit = vl.begin(); vlit != vl.end(); ++vlit ) {
- if ( vlist != "" ) vlist += ";";
- vlist += *vlit;
- }
- versions[ it->first ] = vlist;
- aLength1 += it->first.size() + vlist.size() + 2;
- }
-
- unitsSize = units.size();
- commentSize = comment.size();
-
- //string format:
- //locked flag, modified flag,
- //minutes, hours, day, months, year, user name, char(1),
- //minutes, hours, day, months, year, user name, char(1),
- //.....................................................,
- //.....................................................,
- //.....................................................,
- //minutes, hours, day, months, year, user name, char(1), char(30) <- !!!! used to define end of section with modifications !!!!
- //units, char(1), comment, char(30) <- !!!! used to define start of section with components' versions !!!!
- //component=versions, char(1),
- //component=versions, char(1),
- //...........................,
- //component=versions, char(1), char(0)
-
- //string length: 1 byte = locked flag, 1 byte = modified flag, (12 + name length + 1) for each name and date, 1 byte (char(30) section delimeter)
- // unit length + 1, comment length, "zero" byte
-
- char* aProperty = new char[3 + aLength + 12 * aNames.size() + 1 + unitsSize + 1 + commentSize + 1 + aLength1 ];
-
- sprintf(aProperty,"%c%c", (char)aProp->GetCreationMode(), (aProp->IsLocked())?'l':'u');
-
- aLength = aNames.size();
- int a = 2;
- for(anIndex = 0; anIndex<aLength; anIndex++) {
- sprintf(&(aProperty[a]),"%2d%2d%2d%2d%4d%s",
- (int)(aMinutes[anIndex]),
- (int)(aHours[anIndex]),
- (int)(aDays[anIndex]),
- (int)(aMonths[anIndex]),
- (int)(aYears[anIndex]),
- aNames[anIndex].c_str());
- a = strlen(aProperty);
- aProperty[a++] = 1;
- }
-
- //Write delimeter of the section to define end of the modifications section
- aProperty[a++] = 30;
-
- //Write units if need
- if(units.size() > 0) {
- sprintf(&(aProperty[a]),"%s",units.c_str());
- a = strlen(aProperty);
- }
-
- aProperty[a++] = 1;
-
- //Write comments if need
- if(comment.size() > 0) {
- sprintf(&(aProperty[a]),"%s",comment.c_str());
- a = strlen(aProperty);
- }
-
- aProperty[a++] = 30; //delimeter of the component versions
-
- std::map<std::string, std::string>::const_iterator versionsIt;
- for ( versionsIt = versions.begin(); versionsIt != versions.end(); ++versionsIt ) {
- sprintf(&(aProperty[a]),"%s=%s",
- (char*)(versionsIt->first.c_str()),
- (char*)(versionsIt->second.c_str()));
- a = a + versionsIt->first.size() + versionsIt->second.size() + 1;
- aProperty[a++] = 1;
- }
-
- aProperty[a] = 0;
-
- name_len = (hdf_int32) a;
- size[0] = name_len + 1 ;
- hdf_dataset = new HDFdataset("AttributeStudyProperties",hdf_group,HDF_STRING,size,1);
- hdf_dataset->CreateOnDisk();
- hdf_dataset->WriteOnDisk(aProperty);
- hdf_dataset->CloseOnDisk();
- hdf_dataset=0; //will be deleted by hdf_sco_group destructor
- delete [] aProperty;
-
- aProp->SetModified(0);
- return true;
-}
-
-//=============================================================================
-/*! Function : _SaveAs
- * Purpose : save the study in HDF file
- */
-//============================================================================
-bool SALOMEDSImpl_StudyManager::Impl_SaveAs(const std::string& aStudyUrl,
- SALOMEDSImpl_Study* aStudy,
- SALOMEDSImpl_DriverFactory* aFactory,
- bool theMultiFile,
- bool theASCII)
-{
- // Set "C" locale temporarily to avoid possible localization problems
- Kernel_Utils::Localizer loc;
-
- // HDF File will be composed of differents part :
- // * For each ComponentDataType, all data created by the component
- // Informations in data group hdf_group_datacomponent
- // * Study Structure -> Exactly what is contained in Document
- // Informations in data group hdf_group_study_structure
-
- _errorCode = "";
-
- HDFfile *hdf_file=0;
- HDFgroup *hdf_group_study_structure =0;
- HDFgroup *hdf_sco_group =0;
- HDFgroup *hdf_sco_group2 =0;
- HDFgroup *hdf_notebook_vars =0;
- HDFgroup *hdf_notebook_var = 0;
-
- HDFgroup *hdf_group_datacomponent =0;
- HDFdataset *hdf_dataset =0;
- hdf_size size[1];
- hdf_int32 name_len = 0;
- std::string component_name;
-
- if(!aStudy) {
- _errorCode = "Study is null";
- return false;
- }
-
- // Store previous URL
- std::string anOldName = aStudy->Name();
-
- // Map to store components' versions
- std::map<std::string, std::string> componentVersions;
-
- //Create a temporary url to which the study is saved
- std::string aUrl = SALOMEDSImpl_Tool::GetTmpDir() + SALOMEDSImpl_Tool::GetNameFromPath(aStudyUrl);
-
- // unlock study if it is locked, as some attributes need to be modified
- StudyUnlocker unlock(aStudy);
-
- SALOMEDSImpl_StudyBuilder* SB= aStudy->NewBuilder();
- std::map<std::string, SALOMEDSImpl_Driver*> aMapTypeDriver;
-
- try
- {
- // mpv 15.12.2003: for saving components we have to load all data from all modules
- SALOMEDSImpl_SComponentIterator itcomponent = aStudy->NewComponentIterator();
- for (; itcomponent.More(); itcomponent.Next())
- {
- SALOMEDSImpl_SComponent sco = itcomponent.Value();
- // if there is an associated Engine call its method for saving
- std::string IOREngine;
- try {
- SALOMEDSImpl_Driver* aDriver = NULL;
- std::string aCompType = sco.GetComment();
- if (!sco.ComponentIOR(IOREngine)) {
- if (!aCompType.empty()) {
-
- aDriver = aFactory->GetDriverByType(aCompType);
-
- if (aDriver != NULL) {
- if(!SB->LoadWith(sco, aDriver)) {
- _errorCode = SB->GetErrorCode();
- return false;
- }
- }
- }
- }
- else {
- aDriver = aFactory->GetDriverByIOR(IOREngine);
- }
- aMapTypeDriver[aCompType] = aDriver;
- } catch(...) {
- _errorCode = "Can not restore information to resave it";
- return false;
- }
- }
-
- // VSR: set URL to new file name
- // VSR: remember to set previous name if save operation fails
- aStudy->URL(aStudyUrl);
-
- // To change for Save
- // Do not have to do a new file but just a Open??? Rewrite all informations after erasing evrything??
- hdf_file = new HDFfile((char*)aUrl.c_str());
- hdf_file->CreateOnDisk();
-
- //-----------------------------------------------------------------------
- // 1 - Create a groupe for each SComponent and Update the PersistanceRef
- //-----------------------------------------------------------------------
- hdf_group_datacomponent = new HDFgroup("DATACOMPONENT",hdf_file);
- hdf_group_datacomponent->CreateOnDisk();
-
- for (itcomponent.Init(); itcomponent.More(); itcomponent.Next())
- {
- SALOMEDSImpl_SComponent sco = itcomponent.Value();
-
- std::string scoid = sco.GetID();
- hdf_sco_group = new HDFgroup((char*)scoid.c_str(), hdf_group_datacomponent);
- hdf_sco_group->CreateOnDisk();
-
- std::string componentDataType = sco.ComponentDataType();
- std::string IOREngine;
- if (sco.ComponentIOR(IOREngine))
- {
- // Engine should be already in the map as it was to added before
- SALOMEDSImpl_Driver* Engine = aMapTypeDriver[componentDataType];
- if (Engine != NULL)
- {
- SALOMEDSImpl_TMPFile* aStream = NULL;
- long length = 0;
-
- componentVersions[ componentDataType ] = Engine->Version();
-
- if (theASCII) aStream = Engine->SaveASCII(sco,
- SALOMEDSImpl_Tool::GetDirFromPath(aUrl),
- length,
- theMultiFile);
- else aStream = Engine->Save(sco,
- SALOMEDSImpl_Tool::GetDirFromPath(aUrl),
- length,
- theMultiFile);
- HDFdataset *hdf_dataset;
- hdf_size aHDFSize[1];
- if(length > 0) { //The component saved some auxiliary files, then put them into HDF file
-
- aHDFSize[0] = length;
-
- HDFdataset *hdf_dataset = new HDFdataset("FILE_STREAM", hdf_sco_group, HDF_STRING, aHDFSize, 1);
- hdf_dataset->CreateOnDisk();
- hdf_dataset->WriteOnDisk(aStream->Data()); //Save the stream in the HDF file
- hdf_dataset->CloseOnDisk();
- }
-
- if(aStream) delete aStream;
-
- // store multifile state
- aHDFSize[0] = 2;
- hdf_dataset = new HDFdataset("MULTIFILE_STATE", hdf_sco_group, HDF_STRING, aHDFSize, 1);
- hdf_dataset->CreateOnDisk();
- hdf_dataset->WriteOnDisk((void*)(theMultiFile?"M":"S")); // save: multi or single
- hdf_dataset->CloseOnDisk();
- hdf_dataset=0; //will be deleted by hdf_sco_AuxFiles destructor
- // store ASCII state
- aHDFSize[0] = 2;
- hdf_dataset = new HDFdataset("ASCII_STATE", hdf_sco_group, HDF_STRING, aHDFSize, 1);
- hdf_dataset->CreateOnDisk();
- hdf_dataset->WriteOnDisk((void*)(theASCII?"A":"B")); // save: ASCII or BINARY
- hdf_dataset->CloseOnDisk();
- hdf_dataset=0; //will be deleted by hdf_sco_AuxFiles destructor
- // Creation of the persistance reference attribute
- Translate_IOR_to_persistentID (sco, Engine, theMultiFile, theASCII);
- }
- }
- hdf_sco_group->CloseOnDisk();
- hdf_sco_group=0; // will be deleted by hdf_group_datacomponent destructor
- }
- hdf_group_datacomponent->CloseOnDisk();
- hdf_group_datacomponent =0; // will be deleted by hdf_file destructor
-
- //-----------------------------------------------------------------------
- //3 - Write the Study Structure
- //-----------------------------------------------------------------------
- hdf_group_study_structure = new HDFgroup("STUDY_STRUCTURE",hdf_file);
- hdf_group_study_structure->CreateOnDisk();
- // save component attributes
- for (itcomponent.Init(); itcomponent.More(); itcomponent.Next())
- {
- SALOMEDSImpl_SComponent SC = itcomponent.Value();
- std::string scid = SC.GetID();
- hdf_sco_group2 = new HDFgroup((char*)scid.c_str(), hdf_group_study_structure);
- hdf_sco_group2->CreateOnDisk();
- SaveAttributes(SC, hdf_sco_group2);
- // ComponentDataType treatment
- component_name = SC.ComponentDataType();
- name_len = (hdf_int32)component_name.length();
- size[0] = name_len +1 ;
- hdf_dataset = new HDFdataset("COMPONENTDATATYPE",hdf_sco_group2,HDF_STRING,size,1);
- hdf_dataset->CreateOnDisk();
- hdf_dataset->WriteOnDisk((char*)component_name.c_str());
- hdf_dataset->CloseOnDisk();
- hdf_dataset=0; //will be deleted by hdf_sco_group destructor
- Impl_SaveObject(SC, hdf_sco_group2);
- hdf_sco_group2->CloseOnDisk();
- hdf_sco_group2=0; // will be deleted by hdf_group_study_structure destructor
- }
- //-----------------------------------------------------------------------
- //4 - Write the Study UseCases Structure
- //-----------------------------------------------------------------------
- SALOMEDSImpl_SObject aSO = aStudy->FindObjectID(USE_CASE_LABEL_ID);
- if (aSO) {
- HDFgroup *hdf_soo_group = new HDFgroup(USE_CASE_LABEL_ID,hdf_group_study_structure);
- hdf_soo_group->CreateOnDisk();
- SaveAttributes(aSO, hdf_soo_group);
- Impl_SaveObject(aSO, hdf_soo_group);
- hdf_soo_group->CloseOnDisk();
- hdf_soo_group=0; // will be deleted by hdf_group_study_structure destructor
- }
- //-----------------------------------------------------------------------
- //5 - Write the NoteBook Variables
- //-----------------------------------------------------------------------
-
- //5.1 Create group to store all note book variables
- hdf_notebook_vars = new HDFgroup("NOTEBOOK_VARIABLES",hdf_file);
- hdf_notebook_vars->CreateOnDisk();
-
- std::string varValue;
- std::string varType;
- std::string varIndex;
-
- for(int i=0 ;i < aStudy->myNoteBookVars.size(); i++ ){
- // For each variable create HDF group
- hdf_notebook_var = new HDFgroup((char*)aStudy->myNoteBookVars[i]->Name().c_str(),hdf_notebook_vars);
- hdf_notebook_var->CreateOnDisk();
-
- // Save Variable type
- varType = aStudy->myNoteBookVars[i]->SaveType();
- name_len = (hdf_int32) varType.length();
- size[0] = name_len +1 ;
- hdf_dataset = new HDFdataset("VARIABLE_TYPE",hdf_notebook_var,HDF_STRING,size,1);
- hdf_dataset->CreateOnDisk();
- hdf_dataset->WriteOnDisk((char*)varType.c_str());
- hdf_dataset->CloseOnDisk();
- hdf_dataset=0; //will be deleted by hdf_sco_group destructor
-
- char buffer[256];
- sprintf(buffer,"%d",i);
- varIndex= std::string(buffer);
- name_len = (hdf_int32) varIndex.length();
- size[0] = name_len +1 ;
- hdf_dataset = new HDFdataset("VARIABLE_INDEX",hdf_notebook_var,HDF_STRING,size,1);
- hdf_dataset->CreateOnDisk();
- hdf_dataset->WriteOnDisk((char*)varIndex.c_str());
- hdf_dataset->CloseOnDisk();
- hdf_dataset=0; //will be deleted by hdf_sco_group destructor
-
-
- // Save Variable value
- varValue = aStudy->myNoteBookVars[i]->Save();
- name_len = (hdf_int32) varValue.length();
- size[0] = name_len +1 ;
- hdf_dataset = new HDFdataset("VARIABLE_VALUE",hdf_notebook_var,HDF_STRING,size,1);
- hdf_dataset->CreateOnDisk();
- hdf_dataset->WriteOnDisk((char*)varValue.c_str());
- hdf_dataset->CloseOnDisk();
- hdf_dataset=0; //will be deleted by hdf_sco_group destructor
- hdf_notebook_var->CloseOnDisk();
- hdf_notebook_var = 0; //will be deleted by hdf_sco_group destructor
- }
- hdf_notebook_vars->CloseOnDisk();
- hdf_notebook_vars = 0; //will be deleted by hdf_sco_group destructor
-
- // record component versions
- std::map<std::string, std::string>::const_iterator itVersions;
- for ( itVersions = componentVersions.begin(); itVersions != componentVersions.end(); ++itVersions )
- aStudy->GetProperties()->SetComponentVersion( itVersions->first, itVersions->second );
-
- // lock study back if it was locked initially, to write correct value of Locked flag
- unlock.suspend();
-
- //-----------------------------------------------------------------------
- //6 - Write the Study Properties
- //-----------------------------------------------------------------------
- std::string study_name = aStudy->Name();
- name_len = (hdf_int32) study_name.size();
- size[0] = name_len +1 ;
- hdf_dataset = new HDFdataset("STUDY_NAME",hdf_group_study_structure,HDF_STRING,size,1);
- hdf_dataset->CreateOnDisk();
- hdf_dataset->WriteOnDisk((char*)study_name.c_str());
- hdf_dataset->CloseOnDisk();
- hdf_dataset=0; // will be deleted by hdf_group_study_structure destructor
-
- Impl_SaveProperties(aStudy, hdf_group_study_structure);
- hdf_group_study_structure->CloseOnDisk();
- hdf_file->CloseOnDisk();
-
- hdf_group_study_structure =0; // will be deleted by hdf_file destructor
- delete hdf_file; // recursively deletes all hdf objects...
- }
- catch (HDFexception)
- {
- _errorCode = "HDFexception ! ";
- aStudy->URL( anOldName ); // VSR: restore previous url if operation is failed
- return false;
- }
- catch(std::exception& exc)
- {
- _errorCode = const_cast<char*>(exc.what());
- aStudy->URL( anOldName ); // VSR: restore previous url if operation is failed
- return false;
- }
- catch(...)
- {
- _errorCode = "Unknown exception ! ";
- aStudy->URL( anOldName ); // VSR: restore previous url if operation is failed
- return false;
- }
- if (theASCII) { // save file in ASCII format
- HDFascii::ConvertFromHDFToASCII(aUrl.c_str(), true);
- }
-
- //Now it's necessary to copy files from the temporary directory to the user defined directory.
-
- // The easiest way to get a list of file in the temporary directory
-
- std::string aCmd, aTmpFileDir = SALOMEDSImpl_Tool::GetTmpDir();
- std::string aTmpFile = aTmpFileDir +"files";
- std::string aStudyTmpDir = SALOMEDSImpl_Tool::GetDirFromPath(aUrl);
-
-#ifdef WIN32
- aCmd = "dir /B \"" + aStudyTmpDir +"\" > " + aTmpFile;
-#else
- aCmd ="ls -1 \"" + aStudyTmpDir +"\" > " + aTmpFile;
-#endif
- system(aCmd.c_str());
-
- // Iterate and move files in the temporary directory
- FILE* fp = fopen(aTmpFile.c_str(), "rb");
- if(!fp) {
- aStudy->URL( anOldName ); // VSR: restore previous url if operation is failed
- return false;
- }
- char* buffer = new char[2047];
- int errors = 0;
- while(!feof(fp) && !errors) {
- if((fgets(buffer, 2046, fp)) == NULL) break;
- size_t aLen = strlen(buffer);
- if(buffer[aLen-1] == '\n') buffer[aLen-1] = char(0);
-#ifdef WIN32
- aCmd = "move /Y \"" + aStudyTmpDir + std::string(buffer) + "\" \"" + SALOMEDSImpl_Tool::GetDirFromPath(aStudyUrl) +"\"";
-#else
- aCmd = "mv -f \"" + aStudyTmpDir + std::string(buffer) + "\" \"" + SALOMEDSImpl_Tool::GetDirFromPath(aStudyUrl)+"\"";
-#endif
- errors = system(aCmd.c_str());
- }
-
- delete []buffer;
- fclose(fp);
-
- // Perform cleanup
-#ifdef WIN32
- DeleteFileA(aTmpFile.c_str());
-#else
- unlink(aTmpFile.c_str());
-#endif
-
-#ifdef WIN32
- RemoveDirectoryA(aTmpFileDir.c_str());
- RemoveDirectoryA(aStudyTmpDir.c_str());
-#else
- rmdir(aTmpFileDir.c_str());
- rmdir(aStudyTmpDir.c_str());
-#endif
-
- if ( !errors ) {
- // VSR: finally, if all is done without errors, mark study as Saved
- aStudy->IsSaved(true);
- }
-
- return !errors;
-}
-
-//============================================================================
-/*! Function : Impl_SaveObject
- * Purpose :
- */
-//============================================================================
-bool SALOMEDSImpl_StudyManager::Impl_SaveObject(const SALOMEDSImpl_SObject& SC,
- HDFgroup *hdf_group_datatype)
-{
- _errorCode = "";
-
- // Write in group hdf_group_datatype all informations of SObject SC
- // Iterative function to parse all SObjects under a SComponent
-
- HDFgroup *hdf_group_sobject = 0;
-
- DF_ChildIterator itchild(SC.GetLabel());
- for (; itchild.More(); itchild.Next())
- {
-
- // mpv: don't save empty labels
- std::vector<DF_Attribute*> attr = itchild.Value().GetAttributes();
- if (attr.size() == 0) { //No attributes on the label
- DF_ChildIterator subchild(itchild.Value());
- if (!subchild.More()) {
- continue;
- }
- subchild.Init(itchild.Value(), true);
- bool anEmpty = true;
- for (; subchild.More() && anEmpty; subchild.Next()) {
- std::vector<DF_Attribute*> attr2 = subchild.Value().GetAttributes();
- if (attr2.size()) {
- anEmpty = false; //There are attributes on the child label
- break;
- }
- }
- if (anEmpty) continue;
- }
-
- SALOMEDSImpl_SObject SO = SALOMEDSImpl_Study::SObject(itchild.Value());
-
- std::string scoid = SO.GetID();
- hdf_group_sobject = new HDFgroup(scoid.c_str(), hdf_group_datatype);
- hdf_group_sobject->CreateOnDisk();
- SaveAttributes(SO, hdf_group_sobject);
- Impl_SaveObject(SO, hdf_group_sobject);
- hdf_group_sobject->CloseOnDisk();
- hdf_group_sobject =0; // will be deleted by father hdf object destructor
- }
-
- return true;
-}
-
-//============================================================================
-/*! Function : Impl_SubstituteSlash
- * Purpose :
- */
-//============================================================================
-std::string SALOMEDSImpl_StudyManager::Impl_SubstituteSlash(const std::string& aUrl)
-{
- _errorCode = "";
-
- std::string theUrl(aUrl);
- for(int i = 0; i<theUrl.size(); i++)
- if(theUrl[i] == '/') theUrl[i] = ':';
- return theUrl;
-}
-
-//============================================================================
-/*! Function : GetDocumentOfStudy
- * Purpose :
- */
-//============================================================================
-DF_Document* SALOMEDSImpl_StudyManager::GetDocumentOfStudy(SALOMEDSImpl_Study* theStudy)
-{
- _errorCode = "";
- return theStudy->_doc;
-}
-
-//============================================================================
-/*! Function : CanCopy
- * Purpose :
- */
-//============================================================================
-bool SALOMEDSImpl_StudyManager::CanCopy(const SALOMEDSImpl_SObject& theObject,
- SALOMEDSImpl_Driver* theEngine)
-{
- _errorCode = "";
- SALOMEDSImpl_SComponent aComponent = theObject.GetFatherComponent();
- if (!aComponent) return false;
- if (aComponent.GetLabel() == theObject.GetLabel()) return false;
- std::string IOREngine;
- if (!aComponent.ComponentIOR(IOREngine)) return false;
- if (theEngine == NULL) return false;
- return theEngine->CanCopy(theObject);
-}
-
-//============================================================================
-/*! Function : CopyLabel
- * Purpose :
- */
-//============================================================================
-bool SALOMEDSImpl_StudyManager::CopyLabel(SALOMEDSImpl_Study* theSourceStudy,
- SALOMEDSImpl_Driver* theEngine,
- const int theSourceStartDepth,
- const DF_Label& theSource,
- const DF_Label& theDestinationMain)
-{
- _errorCode = "";
-
- int a;
- DF_Label aTargetLabel = theDestinationMain;
- DF_Label aAuxTargetLabel = theDestinationMain.Father().FindChild(2);
- for(a = theSource.Depth() - theSourceStartDepth; a > 0 ; a--) {
- DF_Label aSourceLabel = theSource;
- for(int aNbFather = 1; aNbFather < a; aNbFather++) aSourceLabel = aSourceLabel.Father();
- aTargetLabel = aTargetLabel.FindChild(aSourceLabel.Tag());
- aAuxTargetLabel = aAuxTargetLabel.FindChild(aSourceLabel.Tag());
- }
- // iterate attributes
- std::vector<DF_Attribute*> attrList = theSource.GetAttributes();
- for(int i = 0, len = attrList.size(); i<len; i++) {
- DF_Attribute* anAttr = attrList[i];
- std::string type = SALOMEDSImpl_GenericAttribute::Impl_GetType(anAttr);
- if (type.substr(0, 17) == std::string("AttributeTreeNode")) continue; // never copy tree node attribute
- if (type == std::string("AttributeTarget")) continue; // and target attribute
-
- if (type == std::string("AttributeReference")) { // reference copied as Comment in aux tree
- DF_Label aReferenced = dynamic_cast<SALOMEDSImpl_AttributeReference*>(anAttr)->Get();
- std::string anEntry = aReferenced.Entry();
- // store the value of name attribute of referenced label
- SALOMEDSImpl_AttributeName* aNameAttribute;
- if ((aNameAttribute=(SALOMEDSImpl_AttributeName*)aReferenced.FindAttribute(SALOMEDSImpl_AttributeName::GetID()))) {
- anEntry += " ";
- anEntry += aNameAttribute->Value();
- }
- SALOMEDSImpl_AttributeComment::Set(aAuxTargetLabel, anEntry);
- continue;
- }
-
- if (type == std::string("AttributeIOR")) { // IOR => ID and TMPFile of Engine
- std::string anEntry = theSource.Entry();
- SALOMEDSImpl_SObject aSO = theSourceStudy->FindObjectID(anEntry);
- int anObjID;
- long aLen;
- SALOMEDSImpl_TMPFile* aStream = theEngine->CopyFrom(aSO, anObjID, aLen);
- std::string aResStr("");
- for(a = 0; a < aLen; a++) {
- aResStr += (char)(aStream->Get(a));
- }
-
- if(aStream) delete aStream;
-
- SALOMEDSImpl_AttributeInteger::Set(aAuxTargetLabel, anObjID);
- SALOMEDSImpl_AttributeName::Set(aAuxTargetLabel, aResStr);
- continue;
- }
- DF_Attribute* aNewAttribute = anAttr->NewEmpty();
- aTargetLabel.AddAttribute(aNewAttribute);
- anAttr->Paste(aNewAttribute);
- }
-
- return true;
-}
-
-//============================================================================
-/*! Function : Copy
- * Purpose :
- */
-//============================================================================
-bool SALOMEDSImpl_StudyManager::Copy(const SALOMEDSImpl_SObject& theObject,
- SALOMEDSImpl_Driver* theEngine)
-{
- _errorCode = "";
-
- // adoptation for alliances datamodel copy: without IOR attributes !!!
- bool aStructureOnly; // copy only SObjects and attributes without component help
- aStructureOnly = !theObject.GetLabel().IsAttribute(SALOMEDSImpl_AttributeIOR::GetID());
-
- // get component-engine
- SALOMEDSImpl_Study* aStudy = theObject.GetStudy();
-
- // CAF document of current study usage
- DF_Document* aDocument = GetDocumentOfStudy(aStudy);
- if (!aDocument) {
- _errorCode = "Document is null";
- return false;
- }
-
- //Clear the clipboard
- _clipboard->Main().Root().ForgetAllAttributes(true);
- _appli->Close(_clipboard);
- _clipboard = _appli->NewDocument("SALOME_STUDY");
-
- // set component data type to the name attribute of root label
- if (!aStructureOnly) {
- SALOMEDSImpl_AttributeComment::Set(_clipboard->Main().Root(),
- theEngine->ComponentDataType());
- }
- // set to the Root label integer attribute: study id
- SALOMEDSImpl_AttributeInteger::Set(_clipboard->Main().Root(), aStudy->StudyId());
- // iterate all theObject's label children
- DF_Label aStartLabel = theObject.GetLabel();
- int aSourceStartDepth = aStartLabel.Depth();
-
- // copy main source label
- CopyLabel(aStudy, theEngine, aSourceStartDepth, aStartLabel, _clipboard->Main());
-
- // copy all subchildren of the main source label (all levels)
- DF_ChildIterator anIterator(aStartLabel, true);
- for(; anIterator.More(); anIterator.Next()) {
- CopyLabel(aStudy, theEngine, aSourceStartDepth, anIterator.Value(), _clipboard->Main());
- }
-
- return true;
-}
-//============================================================================
-/*! Function : CanPaste
- * Purpose :
- */
-//============================================================================
-bool SALOMEDSImpl_StudyManager::CanPaste(const SALOMEDSImpl_SObject& theObject,
- SALOMEDSImpl_Driver* theEngine)
-{
- _errorCode = "";
-
- if (!_clipboard) {
- _errorCode = "Clipboard is null";
- return false;
- }
-
- SALOMEDSImpl_AttributeComment* aCompName = NULL;
- if (!(aCompName=(SALOMEDSImpl_AttributeComment*)_clipboard->Main().Root().FindAttribute(SALOMEDSImpl_AttributeComment::GetID()))) {
- _errorCode = "Clipboard has no component type";
- return false;
- }
- SALOMEDSImpl_AttributeInteger* anObjID;
- if (!(anObjID=(SALOMEDSImpl_AttributeInteger*)_clipboard->Main().Father().FindChild(2).FindAttribute(SALOMEDSImpl_AttributeInteger::GetID()))) {
- _errorCode = "Clipboard has no object id";
- return false;
- }
- SALOMEDSImpl_SComponent aComponent = theObject.GetFatherComponent();
- if (!aComponent) {
- _errorCode = "Object doesn't belong to component";
- return false;
- }
-
- std::string IOREngine;
- if (!aComponent.ComponentIOR(IOREngine)) {
- _errorCode = "component has no IOR";
- return false;
- }
- return theEngine->CanPaste(aCompName->Value(), anObjID->Value());
-}
-
-//============================================================================
-/*! Function : PasteLabel
- * Purpose :
- */
-//============================================================================
-DF_Label SALOMEDSImpl_StudyManager::PasteLabel(SALOMEDSImpl_Study* theDestinationStudy,
- SALOMEDSImpl_Driver* theEngine,
- const DF_Label& theSource,
- const DF_Label& theDestinationStart,
- const int theCopiedStudyID,
- const bool isFirstElement)
-{
- _errorCode = "";
-
- // get corresponding source, target and auxiliary labels
- DF_Label aTargetLabel = theDestinationStart;
-
- DF_Label aAuxSourceLabel = theSource.Root().FindChild(2);
- int a;
- if (!isFirstElement) {
- for(a = theSource.Depth() - 1; a > 0 ; a--) {
- DF_Label aSourceLabel = theSource;
- for(int aNbFather = 1; aNbFather < a; aNbFather++) aSourceLabel = aSourceLabel.Father();
- aTargetLabel = aTargetLabel.FindChild(aSourceLabel.Tag());
- aAuxSourceLabel = aAuxSourceLabel.FindChild(aSourceLabel.Tag());
- }
- SALOMEDSImpl_SObject so = theDestinationStudy->GetSObject(aTargetLabel);
- theDestinationStudy->addSO_Notification(so);
- }
-
- // check auxiliary label for TMPFile => IOR
- SALOMEDSImpl_AttributeName* aNameAttribute = NULL;
- if ((aNameAttribute=(SALOMEDSImpl_AttributeName*)aAuxSourceLabel.FindAttribute(SALOMEDSImpl_AttributeName::GetID()))) {
- SALOMEDSImpl_AttributeInteger* anObjID = (SALOMEDSImpl_AttributeInteger*)aAuxSourceLabel.FindAttribute(SALOMEDSImpl_AttributeInteger::GetID());
- SALOMEDSImpl_AttributeComment* aComponentName = (SALOMEDSImpl_AttributeComment*)theSource.Root().FindAttribute(SALOMEDSImpl_AttributeComment::GetID());
- std::string aCompName = aComponentName->Value();
-
- if (theEngine->CanPaste(aCompName, anObjID->Value())) {
- std::string aTMPStr = aNameAttribute->Value();
- int aLen = aTMPStr.size();
- unsigned char* aStream = NULL;
- if(aLen > 0) {
- aStream = new unsigned char[aLen+10];
- for(a = 0; a < aLen; a++) {
- aStream[a] = aTMPStr[a];
- }
- }
-
- std::string anEntry = aTargetLabel.Entry();
- SALOMEDSImpl_SObject aPastedSO = theDestinationStudy->FindObjectID(anEntry);
-
- if (isFirstElement) {
- std::string aDestEntry = theEngine->PasteInto(aStream,
- aLen,
- anObjID->Value(),
- aPastedSO.GetFatherComponent());
- aTargetLabel = DF_Label::Label(theDestinationStart, aDestEntry);
- } else
- theEngine->PasteInto(aStream, aLen, anObjID->Value(), aPastedSO);
-
- if(aStream != NULL) delete []aStream;
- }
- }
-
- // iterate attributes
- std::vector<DF_Attribute*> attrList = theSource.GetAttributes();
- for(int i = 0, len = attrList.size(); i<len; i++) {
- DF_Attribute* anAttr = attrList[i];
- if (aTargetLabel.FindAttribute(anAttr->ID())) {
- aTargetLabel.ForgetAttribute(anAttr->ID());
- }
- DF_Attribute* aNewAttribute = anAttr->NewEmpty();
- aTargetLabel.AddAttribute(aNewAttribute);
- anAttr->Paste(aNewAttribute);
- }
-
- // check auxiliary label for Comment => reference or name attribute of the referenced object
- SALOMEDSImpl_AttributeComment* aCommentAttribute = NULL;
- if ((aCommentAttribute=(SALOMEDSImpl_AttributeComment*)aAuxSourceLabel.FindAttribute(SALOMEDSImpl_AttributeComment::GetID()))) {
- char * anEntry = new char[aCommentAttribute->Value().size() + 1];
- strcpy(anEntry, std::string(aCommentAttribute->Value()).c_str());
- char* aNameStart = strchr(anEntry, ' ');
- if (aNameStart) {
- *aNameStart = '\0';
- aNameStart++;
- }
- if (theCopiedStudyID == theDestinationStudy->StudyId()) { // if copy to the same study, reanimate reference
- DF_Label aRefLabel = DF_Label::Label(aTargetLabel, anEntry);
- SALOMEDSImpl_AttributeReference::Set(aTargetLabel, aRefLabel);
- // target attributes structure support
- SALOMEDSImpl_AttributeTarget::Set(aRefLabel)->Add(SALOMEDSImpl_Study::SObject(aTargetLabel));
- } else {
- if (aNameStart) SALOMEDSImpl_AttributeName::Set(aTargetLabel, aNameStart);
- else SALOMEDSImpl_AttributeName::Set(aTargetLabel, std::string("Reference to:")+anEntry);
- }
- delete [] anEntry;
- }
-
- return aTargetLabel;
-}
-
-//============================================================================
-/*! Function : Paste
- * Purpose :
- */
-//============================================================================
-SALOMEDSImpl_SObject SALOMEDSImpl_StudyManager::Paste(const SALOMEDSImpl_SObject& theObject,
- SALOMEDSImpl_Driver* theEngine)
-{
- _errorCode = "";
-
- SALOMEDSImpl_SObject so;
- SALOMEDSImpl_Study* aStudy = theObject.GetStudy();
-
- // if study is locked, then paste can't be done
- if (aStudy->GetProperties()->IsLocked()) {
- _errorCode = "LockProtection";
- throw LockProtection("LockProtection");
- }
-
- // if there is no component name, then paste only SObjects and attributes: without component help
- SALOMEDSImpl_AttributeComment* aComponentName = NULL;
- bool aStructureOnly = !(aComponentName=(SALOMEDSImpl_AttributeComment*)_clipboard->Main().Root().FindAttribute(SALOMEDSImpl_AttributeComment::GetID()));
-
- // get copied study ID
- SALOMEDSImpl_AttributeInteger* aStudyIDAttribute = NULL;
- if (!(aStudyIDAttribute=(SALOMEDSImpl_AttributeInteger*)_clipboard->Main().Root().FindAttribute(SALOMEDSImpl_AttributeInteger::GetID()))) {
- _errorCode = "No study ID was found";
- return so;
- }
- int aCStudyID = aStudyIDAttribute->Value();
-
- // CAF document of current study usage
- DF_Document* aDocument = GetDocumentOfStudy(aStudy);
- if (!aDocument) {
- _errorCode = "Document is null";
- return so;
- }
-
- SALOMEDSImpl_SComponent aComponent = theObject.GetFatherComponent();
-
- // fill root inserted SObject
- DF_Label aStartLabel;
- if (aStructureOnly) {
- DF_Label anObjectLabel = DF_Label::Label(aDocument->Main(), theObject.GetID());
- aStartLabel = PasteLabel(aStudy, theEngine, _clipboard->Main(), anObjectLabel, aCStudyID, false);
- } else {
- DF_Label aComponentLabel = DF_Label::Label(aDocument->Main(), aComponent.GetID());
- aStartLabel = PasteLabel(aStudy, theEngine, _clipboard->Main(), aComponentLabel, aCStudyID, true);
- }
-
- // paste all sublebels
- DF_ChildIterator anIterator(_clipboard->Main(), true);
- for(; anIterator.More(); anIterator.Next()) {
- PasteLabel(aStudy, theEngine, anIterator.Value(), aStartLabel, aCStudyID, false);
- }
-
- return SALOMEDSImpl_Study::SObject(aStartLabel);
-}
-
-//#######################################################################################################
-//# STATIC PRIVATE FUNCTIONS
-//#######################################################################################################
-
-//============================================================================
-/*! Function : SaveAttributes
- * Purpose : Save attributes for object
- */
-//============================================================================
-static void SaveAttributes(const SALOMEDSImpl_SObject& aSO, HDFgroup *hdf_group_sobject)
-{
- hdf_size size[1];
- std::vector<DF_Attribute*> attrList = aSO.GetLabel().GetAttributes();
- DF_Attribute* anAttr = NULL;
- for(int i = 0, len = attrList.size(); i<len; i++) {
- anAttr = attrList[i];
- //The following attributes are not supposed to be written to the file
- std::string type = SALOMEDSImpl_GenericAttribute::Impl_GetType(anAttr);
- if(type == std::string("AttributeIOR")) continue; //IOR attribute is not saved
- std::string aSaveStr =anAttr->Save();
- //cout << "Saving: " << aSO.GetID() << " type: "<< type<<"|" << endl;
- size[0] = (hdf_int32) strlen(aSaveStr.c_str()) + 1;
- HDFdataset *hdf_dataset = new HDFdataset((char*)type.c_str(), hdf_group_sobject, HDF_STRING,size, 1);
- hdf_dataset->CreateOnDisk();
- hdf_dataset->WriteOnDisk((char*)aSaveStr.c_str());
- hdf_dataset->CloseOnDisk();
- hdf_dataset=0; //will be deleted by hdf_sco_group destructor
- }
-}
-
-//===========================================================================
-//Function : ReadAttributes
-//===========================================================================
-static void ReadAttributes(SALOMEDSImpl_Study* theStudy,
- const SALOMEDSImpl_SObject& aSO,
- HDFdataset* hdf_dataset)
-{
- hdf_dataset->OpenOnDisk();
-
- DF_Attribute* anAttr = NULL;
- char* current_string = new char[hdf_dataset->GetSize()+1];
- hdf_dataset->ReadFromDisk(current_string);
- //cout << "Reading attr type = " << hdf_dataset->GetName() << " SO = " << aSO.GetID() << endl;
- if (!strcmp(hdf_dataset->GetName(),"COMPONENTDATATYPE")) {
- anAttr = theStudy->NewBuilder()->FindOrCreateAttribute(aSO, "AttributeComment");
- } else if (!strcmp(hdf_dataset->GetName(),"AttributeReference") ||
- !strcmp(hdf_dataset->GetName(),"Reference")) { // Old format maintainance
- theStudy->NewBuilder()->Addreference(aSO, theStudy->CreateObjectID(current_string));
- delete [] (current_string);
- hdf_dataset->CloseOnDisk();
- return;
- } else {
- anAttr = theStudy->NewBuilder()->FindOrCreateAttribute(aSO, hdf_dataset->GetName());
- }
-
- if (anAttr) {
- anAttr->Load(current_string);
- }
-
- delete [] (current_string);
- hdf_dataset->CloseOnDisk();
-}
-
-//============================================================================
-//Function : BuildlTree
-//============================================================================
-static void BuildTree (SALOMEDSImpl_Study* theStudy, HDFgroup* hdf_current_group)
-{
- hdf_current_group->OpenOnDisk();
- SALOMEDSImpl_SObject aSO;
- char* Entry = hdf_current_group->GetName();
- if (strcmp(Entry,"STUDY_STRUCTURE") == 0) {
- aSO = theStudy->CreateObjectID("0:1");
- }
- else {
- aSO = theStudy->CreateObjectID(Entry);
- }
-
- char name[HDF_NAME_MAX_LEN+1];
- int nbsons = hdf_current_group->nInternalObjects();
- for (int i=0; i<nbsons; i++) {
- hdf_current_group->InternalObjectIndentify(i,name);
- if (strncmp(name, "INTERNAL_COMPLEX",16) == 0) continue;
- hdf_object_type type = hdf_current_group->InternalObjectType(name);
-
- if (type == HDF_DATASET) {
- HDFdataset* new_dataset = new HDFdataset(name,hdf_current_group);
- ReadAttributes(theStudy,aSO,new_dataset);
- new_dataset = 0; // will be deleted by father destructor
-
- }
- else if (type == HDF_GROUP) {
- HDFgroup* new_group = new HDFgroup(name,hdf_current_group);
- BuildTree (theStudy, new_group);
- new_group = 0; // will be deleted by father destructor
- }
- }
- hdf_current_group->CloseOnDisk();
-}
-
-
-//============================================================================
-//Function : Translate_IOR_to_persistentID
-//============================================================================
-static void Translate_IOR_to_persistentID (const SALOMEDSImpl_SObject& so,
- SALOMEDSImpl_Driver* engine,
- bool isMultiFile,
- bool isASCII)
-{
- DF_ChildIterator itchild(so.GetLabel());
- std::string ior_string, persistent_string, curid;
-
- for (; itchild.More(); itchild.Next()) {
- SALOMEDSImpl_SObject current = SALOMEDSImpl_Study::SObject(itchild.Value());
- SALOMEDSImpl_AttributeIOR* IOR = NULL;
- if ((IOR=(SALOMEDSImpl_AttributeIOR*)current.GetLabel().FindAttribute(SALOMEDSImpl_AttributeIOR::GetID()))) {
- ior_string = IOR->Value();
-
- persistent_string = engine->IORToLocalPersistentID (current, ior_string, isMultiFile, isASCII);
- SALOMEDSImpl_AttributePersistentRef::Set(current.GetLabel(), persistent_string);
- }
- Translate_IOR_to_persistentID (current, engine, isMultiFile, isASCII);
- }
-}
-
-void ReadNoteBookVariables(SALOMEDSImpl_Study* theStudy, HDFgroup* theGroup)
-{
- if(!theGroup)
- return;
-
- HDFgroup* new_group =0;
- HDFdataset* new_dataset =0;
-
- char aVarName[HDF_NAME_MAX_LEN+1];
- char *currentVarType = 0;
- char *currentVarValue = 0;
- char *currentVarIndex = 0;
- int order = 0;
- //Open HDF group with notebook variables
- theGroup->OpenOnDisk();
-
- //Get Nb of variables
- int aNbVars = theGroup->nInternalObjects();
-
- std::map<int,SALOMEDSImpl_GenericVariable*> aVarsMap;
-
- for( int iVar=0;iVar < aNbVars;iVar++ ) {
- theGroup->InternalObjectIndentify(iVar,aVarName);
- hdf_object_type type = theGroup->InternalObjectType(aVarName);
- if(type == HDF_GROUP) {
-
- //Read Variable
- new_group = new HDFgroup(aVarName,theGroup);
- new_group->OpenOnDisk();
-
- //Read Type
- new_dataset = new HDFdataset("VARIABLE_TYPE",new_group);
- new_dataset->OpenOnDisk();
- currentVarType = new char[new_dataset->GetSize()+1];
- new_dataset->ReadFromDisk(currentVarType);
- new_dataset->CloseOnDisk();
- new_dataset = 0; //will be deleted by hdf_sco_group destructor
-
- //Read Order
- if(new_group->ExistInternalObject("VARIABLE_INDEX")) {
- new_dataset = new HDFdataset("VARIABLE_INDEX",new_group);
- new_dataset->OpenOnDisk();
- currentVarIndex = new char[new_dataset->GetSize()+1];
- new_dataset->ReadFromDisk(currentVarIndex);
- new_dataset->CloseOnDisk();
- new_dataset = 0; //will be deleted by hdf_sco_group destructor
- order = atoi(currentVarIndex);
- delete [] currentVarIndex;
- }
- else
- order = iVar;
-
- //Read Value
- new_dataset = new HDFdataset("VARIABLE_VALUE",new_group);
- new_dataset->OpenOnDisk();
- currentVarValue = new char[new_dataset->GetSize()+1];
- new_dataset->ReadFromDisk(currentVarValue);
- new_dataset->CloseOnDisk();
- new_dataset = 0; //will be deleted by hdf_sco_group destructor
-
- new_group->CloseOnDisk();
- new_group = 0; //will be deleted by hdf_sco_group destructor
-
- SALOMEDSImpl_GenericVariable::VariableTypes aVarType =
- SALOMEDSImpl_GenericVariable::String2VariableType(std::string(currentVarType));
- delete [] currentVarType;
-
- //Create variable and add it in the study
- SALOMEDSImpl_GenericVariable* aVariable =
- new SALOMEDSImpl_ScalarVariable(aVarType,std::string(aVarName));
- aVariable->Load(std::string(currentVarValue));
- aVarsMap.insert(std::make_pair(order,aVariable));
- delete [] currentVarValue;
- }
- }
-
- std::map<int,SALOMEDSImpl_GenericVariable*>::const_iterator it= aVarsMap.begin();
- for(;it!=aVarsMap.end();it++)
- theStudy->AddVariable((*it).second);
-
- theGroup->CloseOnDisk();
-}
+++ /dev/null
-// 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 : SALOMEDSImpl_StudyManager.hxx
-// Author : Sergey RUIN
-// Module : SALOME
-//
-#ifndef __SALOMEDSImpl_STUDYMANAGER_I_H__
-#define __SALOMEDSImpl_STUDYMANAGER_I_H__
-
-#include "SALOMEDSImpl_Defines.hxx"
-
-// std C++ headers
-#include <sstream>
-#include <string>
-#include <vector>
-
-#include "DF_Application.hxx"
-#include "SALOMEDSImpl_Study.hxx"
-#include "SALOMEDSImpl_SObject.hxx"
-#include "SALOMEDSImpl_Driver.hxx"
-#include "DF_Attribute.hxx"
-#include "DF_Label.hxx"
-#include "DF_Document.hxx"
-
-class HDFgroup;
-
-class SALOMEDSIMPL_EXPORT SALOMEDSImpl_StudyManager
-{
-
-private:
-
- DF_Application* _appli;
- int _IDcounter;
- DF_Document* _clipboard;
- std::string _errorCode;
-
-public:
-
- //! standard constructor
- SALOMEDSImpl_StudyManager();
-
- //! standard destructor
- virtual ~SALOMEDSImpl_StudyManager();
-
- //! method to Create a New Study of name study_name
- virtual SALOMEDSImpl_Study* NewStudy(const std::string& study_name);
-
- //! method to Open a Study from it's persistent reference
- virtual SALOMEDSImpl_Study* Open(const std::string& aStudyUrl);
-
- //! method to close a Study
- virtual void Close(SALOMEDSImpl_Study* aStudy);
-
- //! method to save a Study
- virtual bool Save(SALOMEDSImpl_Study* aStudy, SALOMEDSImpl_DriverFactory* aFactory, bool theMultiFile);
-
- virtual bool SaveASCII(SALOMEDSImpl_Study* aStudy,
- SALOMEDSImpl_DriverFactory* aFactory,
- bool theMultiFile);
-
- //! method to save a Study to the persistent reference aUrl
- virtual bool SaveAs(const std::string& aUrl,
- SALOMEDSImpl_Study* aStudy,
- SALOMEDSImpl_DriverFactory* aFactory,
- bool theMultiFile);
-
- virtual bool SaveAsASCII(const std::string& aUrl,
- SALOMEDSImpl_Study* aStudy,
- SALOMEDSImpl_DriverFactory* aFactory,
- bool theMultiFile);
-
- //! method to Get name list of open studies in the session
- virtual std::vector<SALOMEDSImpl_Study*> GetOpenStudies();
-
- //! method to get a Study from it's name
- virtual SALOMEDSImpl_Study* GetStudyByName(const std::string& aStudyName) ;
-
- //! method to get a Study from it's ID
- virtual SALOMEDSImpl_Study* GetStudyByID(int aStudyID) ;
-
-
- DF_Document* GetDocumentOfStudy(SALOMEDSImpl_Study* theStudy);
-
- DF_Document* GetClipboard() { return _clipboard; }
-
- bool CopyLabel(SALOMEDSImpl_Study* theSourceStudy,
- SALOMEDSImpl_Driver* theEngine,
- const int theSourceStartDepth,
- const DF_Label& theSource,
- const DF_Label& theDestinationMain);
-
- DF_Label PasteLabel(SALOMEDSImpl_Study* theDestinationStudy,
- SALOMEDSImpl_Driver* theEngine,
- const DF_Label& theSource,
- const DF_Label& theDestinationStart,
- const int theCopiedStudyID,
- const bool isFirstElement);
-
- virtual bool CanCopy(const SALOMEDSImpl_SObject& theObject, SALOMEDSImpl_Driver* Engine);
- virtual bool Copy(const SALOMEDSImpl_SObject& theObject, SALOMEDSImpl_Driver* Engine);
- virtual bool CanPaste(const SALOMEDSImpl_SObject& theObject, SALOMEDSImpl_Driver* Engine);
- virtual SALOMEDSImpl_SObject Paste(const SALOMEDSImpl_SObject& theObject, SALOMEDSImpl_Driver* Engine);
-
- // _SaveAs private function called by Save and SaveAs
- virtual bool Impl_SaveAs(const std::string& aUrl,
- SALOMEDSImpl_Study* aStudy,
- SALOMEDSImpl_DriverFactory* aFactory,
- bool theMultiFile,
- bool theASCII);
-
- // _SaveObject private function called by _SaveAs
- virtual bool Impl_SaveObject(const SALOMEDSImpl_SObject& SC, HDFgroup *hdf_group_datatype);
-
- // _SubstituteSlash function called by Open and GetStudyByName
- virtual std::string Impl_SubstituteSlash(const std::string& aUrl);
-
- virtual bool Impl_SaveProperties(SALOMEDSImpl_Study* aStudy, HDFgroup *hdf_group);
-
- std::string GetErrorCode() { return _errorCode; }
- virtual bool IsError() { return _errorCode != ""; }
-
-};
-
-#endif
aCurrentNode->Append(aNode);
// Mantis issue 0020136: Drag&Drop in OB
- theObject.GetStudy()->addSO_Notification(theObject);
+ SALOMEDSImpl_Study::GetStudyImpl(theObject.GetLabel())->addSO_Notification(theObject);
return true;
}
bool ret = aFather->Append(aNode);
// Mantis issue 0020136: Drag&Drop in OB
- theObject.GetStudy()->addSO_Notification(theObject);
+ SALOMEDSImpl_Study::GetStudyImpl(theObject.GetLabel())->addSO_Notification(theObject);
return ret;
}
bool ret = aNode->InsertBefore(aFirstNode);
// Mantis issue 0020136: Drag&Drop in OB
- theFirst.GetStudy()->addSO_Notification(theFirst);
+ SALOMEDSImpl_Study::GetStudyImpl(theFirst.GetLabel())->addSO_Notification(theFirst);
return ret;
}
#include "utilities.h"
#include "SALOMEDSImpl_AttributeParameter.hxx"
-#include "SALOMEDSImpl_StudyManager.hxx"
#include "SALOMEDSImpl_Study.hxx"
#include "SALOMEDSImpl_StudyBuilder.hxx"
#include "SALOMEDSImpl_GenericAttribute.hxx"
// ============================================================================
void SALOMEDSImplTest::testAttributeParameter()
{
- SALOMEDSImpl_StudyManager* sm = new SALOMEDSImpl_StudyManager();
- SALOMEDSImpl_Study* study = sm->NewStudy("Test");
+ SALOMEDSImpl_Study* study = new SALOMEDSImpl_Study();
SALOMEDSImpl_AttributeParameter* _ap = study->GetCommonParameters("TestComp", 0);
CPPUNIT_ASSERT(_ap);
# 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 orbmodule
#include "DF_ChildIterator.hxx"
#include "SALOMEDSImpl_Attributes.hxx"
-#include "SALOMEDSImpl_StudyManager.hxx"
#include "SALOMEDSImpl_Study.hxx"
#include "SALOMEDSImpl_StudyBuilder.hxx"
#include "SALOMEDSImpl_SObject.hxx"
{
std::cout << "Test started " << std::endl;
- SALOMEDSImpl_StudyManager* aSM = new SALOMEDSImpl_StudyManager();
- std::cout << "Manager is created " << std::endl;
- SALOMEDSImpl_Study* aStudy = aSM->NewStudy("SRN");
- std::cout << "Study with id = " << aStudy->StudyId() << " is created " << std::endl;
+ SALOMEDSImpl_Study* aStudy = new SALOMEDSImpl_Study();
+ std::cout << "Study is created" << std::endl;
std::cout << "Check the study lock, locking" << std::endl;
aStudy->SetStudyLock("SRN");
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
-import sys, signal,string,commands
+import sys, signal,string,subprocess
import subprocess
import runSalome
import setenv
# dict,list,tuple,int,float,str
import SALOME
-import cPickle
+import pickle
class List(object):
def __init__(self,varPtr,isTemporaryVar=False):
pass
def assign(self,elt):
- st=cPickle.dumps(elt,cPickle.HIGHEST_PROTOCOL)
+ st=pickle.dumps(elt,pickle.HIGHEST_PROTOCOL)
self._var_ptr.setSerializedContent(st)
pass
return self.local_copy().__repr__()
def local_copy(self):
- return cPickle.loads(self._var_ptr.fetchSerializedContent())
+ return pickle.loads(self._var_ptr.fetchSerializedContent())
def __reduce__(self):
return (list,(self.local_copy(),))
pass
def assign(self,elt):
- st=cPickle.dumps(elt,cPickle.HIGHEST_PROTOCOL)
+ st=pickle.dumps(elt,pickle.HIGHEST_PROTOCOL)
self._var_ptr.setSerializedContent(st)
pass
return self.local_copy().__repr__()
def local_copy(self):
- return cPickle.loads(self._var_ptr.fetchSerializedContent())
+ return pickle.loads(self._var_ptr.fetchSerializedContent())
def __reduce__(self):
return (tuple,(self.local_copy(),))
return ret(*args)
def assign(self,elt):
- st=cPickle.dumps(elt,cPickle.HIGHEST_PROTOCOL)
+ st=pickle.dumps(elt,pickle.HIGHEST_PROTOCOL)
self._var_ptr.setSerializedContent(st)
pass
return self.local_copy().__repr__()
def local_copy(self):
- return cPickle.loads(self._var_ptr.fetchSerializedContent())
+ return pickle.loads(self._var_ptr.fetchSerializedContent())
def __reduce__(self):
return (int,(self.local_copy(),))
pass
def assign(self,elt):
- st=cPickle.dumps(elt,cPickle.HIGHEST_PROTOCOL)
+ st=pickle.dumps(elt,pickle.HIGHEST_PROTOCOL)
self._var_ptr.setSerializedContent(st)
pass
return self.local_copy().__repr__()
def local_copy(self):
- return cPickle.loads(self._var_ptr.fetchSerializedContent())
+ return pickle.loads(self._var_ptr.fetchSerializedContent())
def __reduce__(self):
return (dict,(self.local_copy(),))
pass
def __call__(self,*args):
- ret=self._var_ptr.invokePythonMethodOn(self._meth,cPickle.dumps(args,cPickle.HIGHEST_PROTOCOL))
+ ret=self._var_ptr.invokePythonMethodOn(self._meth,pickle.dumps(args,pickle.HIGHEST_PROTOCOL))
return GetHandlerFromRef(ret,True)
pass
PyHandlerTypeMap={int:Int,list:List,tuple:Tuple,dict:Dict}
def GetHandlerFromRef(objCorba,isTempVar=False):
- v=cPickle.loads(objCorba.fetchSerializedContent())
+ v=pickle.loads(objCorba.fetchSerializedContent())
if v is None:
return None
return PyHandlerTypeMap[v.__class__](objCorba,isTempVar)
std::size_t DataScopeServerBase::COUNTER=0;
+#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
+
void DataScopeKiller::shutdown()
{
Py_Finalize();
{
Py_Initialize();
PyEval_InitThreads();
- PySys_SetArgv(argc,argv);
+ 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);
PyObject *mainmod(PyImport_AddModule("__main__"));
_globals=PyModule_GetDict(mainmod);
if(PyDict_GetItemString(_globals, "__builtins__") == NULL)
}
_locals=PyDict_New();
PyObject *tmp(PyList_New(0));
- _pickler=PyImport_ImportModuleLevel(const_cast<char *>("cPickle"),_globals,_locals,tmp,-1);
+ _pickler=PyImport_ImportModuleLevel(const_cast<char *>("pickle"),_globals,_locals,tmp,0);
}
void DataScopeServerBase::registerToSalomePiDict() const
if(!meth)
{ Py_XDECREF(mod); return ; }
PyObject *args(PyTuple_New(2));
- PyTuple_SetItem(args,0,PyInt_FromLong(getpid()));
- PyTuple_SetItem(args,1,PyString_FromString("SALOME_DataScopeServerBase"));
+ PyTuple_SetItem(args,0,PyLong_FromLong(getpid()));
+ PyTuple_SetItem(args,1,PyUnicode_FromString("SALOME_DataScopeServerBase"));
PyObject *res(PyObject_CallObject(meth,args));
Py_XDECREF(args);
Py_XDECREF(res);
void DataScopeServerTransaction::pingKey(PyObject *keyObj)
{
- PyObject *cmpObj(getPyCmpFunc());
- if(!keyObj)
- throw Exception("ataScopeServerTransaction::pingKey : Key Object is NULL !");
- PyObject *args(PyTuple_New(2));
- PyTuple_SetItem(args,0,keyObj); Py_XINCREF(keyObj);
std::size_t ii(0);
// this part does nothing except to be sure that in notify key all will be OK.
for(std::list< KeyWaiter *>::iterator it=_waiting_keys.begin();it!=_waiting_keys.end();it++,ii++)
{
PyObject *waitKey((*it)->getKeyPyObj());
- PyTuple_SetItem(args,1,waitKey); Py_XINCREF(waitKey);
- PyObject *res(PyObject_CallObject(cmpObj,args));
+ PyObject *res(PyObject_CallMethodObjArgs(keyObj, PyUnicode_DecodeASCII("__ne__", 6, NULL), waitKey));
if(res==NULL)
{
std::ostringstream oss; oss << "DataScopeServerTransaction::pingKey : for object id #" << ii << " error during cmp(k,wk[i]) !";
throw Exception(oss.str());
}
- PyInt_AsLong(res);
+ PyLong_AsLong(res); // res is bool, but it s ok since __int__ is called
if(PyErr_Occurred())
{
std::ostringstream oss; oss << "DataScopeServerTransaction::pingKey : for object id #" << ii << " error during interpretation of cmp(k,wk[i]) !";
void DataScopeServerTransaction::notifyKey(const std::string& varName, PyObject *keyObj, PyObject *valueObj)
{
- PyObject *cmpObj(getPyCmpFunc());
- if(!keyObj)
- throw Exception("DataScopeServerTransaction::notifyKey : MAIN INTERNAL ERROR ! Key Object is NULL !");
- PyObject *args(PyTuple_New(2));
- PyTuple_SetItem(args,0,keyObj); Py_XINCREF(keyObj);
std::size_t ii(0);
std::list< KeyWaiter *> newList,listOfEltToWakeUp;
for(std::list< KeyWaiter *>::iterator it=_waiting_keys.begin();it!=_waiting_keys.end();it++,ii++)
continue;
}
PyObject *waitKey((*it)->getKeyPyObj());
- PyTuple_SetItem(args,1,waitKey); Py_XINCREF(waitKey);
- PyObject *res(PyObject_CallObject(cmpObj,args));
+ PyObject *res(PyObject_CallMethodObjArgs(keyObj, PyUnicode_DecodeASCII("__ne__", 6, NULL), waitKey));
if(res==NULL)
{
std::ostringstream oss; oss << "DataScopeServerTransaction::notifyKey : MAIN INTERNAL ERROR ! for object id #" << ii << " error during cmp(k,wk[i]) !";
throw Exception(oss.str());
}
- long resCpp(PyInt_AsLong(res));
+ long resCpp(PyLong_AsLong(res)); // res is bool, but it s ok since __int__ is called
if(PyErr_Occurred())
{
std::ostringstream oss; oss << "DataScopeServerTransaction::notifyKey : MAIN INTERNAL ERROR ! for object id #" << ii << " error during interpretation of cmp(k,wk[i]) !";
transactionsCpp[i]->notify();
}
-/*!
- * Returns borrowed reference.
- */
-PyObject *DataScopeServerTransaction::getPyCmpFunc()
-{
- PyObject *builtins(PyDict_GetItemString(_globals,"__builtins__"));//borrowed
- if(builtins==NULL)
- throw Exception("Fail to find reference to builtins !");
- PyObject *builtins2(PyModule_GetDict(builtins));//borrowed
- if(builtins2==NULL)
- throw Exception("Fail to invoke __dict__ on builtins !");
- PyObject *cmpObj(PyDict_GetItemString(builtins2,"cmp"));
- if(cmpObj==NULL)
- throw Exception("Fail to find cmp in __builtins__ !");
- return cmpObj;
-}
-
DataScopeServerTransaction::~DataScopeServerTransaction()
{
}
SALOME::KeyWaiter_ptr waitForKeyInVar(const char *varName, const SALOME::ByteVec& keyVal);
SALOME::KeyWaiter_ptr waitForKeyInVarAndKillIt(const char *varName, const SALOME::ByteVec& keyVal, SALOME::Transaction_out transac);
void atomicApply(const SALOME::ListOfTransaction& transactions);
- private:
- PyObject *getPyCmpFunc();
private:
PortableServer::POA_var _poa_for_key_waiter;
std::list< KeyWaiter * > _waiting_keys;
Py_XDECREF(argsPy);
throw Exception("PickelizedPyObjRdExtServer::checkRdExtnessOf : self is NULL !");
}
- if(PyTuple_Check(_self)==1 || PyString_Check(_self)==1 || PyInt_Check(_self)==1 || PyBool_Check(_self)==1 || PyFloat_Check(_self)==1)
+ if(PyTuple_Check(_self)==1 || PyBytes_Check(_self)==1 || PyLong_Check(_self)==1 || PyBool_Check(_self)==1 || PyFloat_Check(_self)==1)
return ;//_self is tuple, str, int or float -> immutable in python. So no method can break the RdExtness of _self.
if(PyList_Check(_self)==1)
checkListRdExtnessOf(methodName,argsPy);
if(errTyp)
{
PyObject *ob(PyObject_Str(errTyp));
- oss2 << " type : \"" << (const char *)PyString_AsString(ob) << "\"";
+ oss2 << " type : \"" << (const char *)PyUnicode_AsUTF8(ob) << "\"";
Py_XDECREF(ob); Py_XDECREF(errTyp);
}
if(errValue)
{
PyObject *ob(PyObject_Str(errValue));
- oss2 << " value : \"" << (const char *)PyString_AsString(ob) << "\"";
+ oss2 << " value : \"" << (const char *)PyUnicode_AsUTF8(ob) << "\"";
Py_XDECREF(ob); Py_XDECREF(errValue);
}
oss2 << " )";
if(errTB)
{
PyObject *ob(PyObject_Str(errTB));
- oss2 << "( traceback : \"" << (const char *)PyString_AsString(ob) << "\"";
+ oss2 << "( traceback : \"" << (const char *)PyUnicode_AsUTF8(ob) << "\"";
Py_XDECREF(ob); Py_XDECREF(errTB);
}
oss2 << " )";
PyObject *PickelizedPyObjServer::GetPyObjFromPickled(const std::string& pickledData, DataScopeServerBase *dsb)
{
std::size_t sz(pickledData.size());
- PyObject *pickledDataPy(PyString_FromStringAndSize(NULL,sz));// agy : do not use PyString_FromString because std::string hides a vector of byte.
- char *buf(PyString_AsString(pickledDataPy));// this buf can be used thanks to python documentation.
+ PyObject *pickledDataPy(PyBytes_FromStringAndSize(NULL,sz));// agy : do not use PyUnicode_FromString because std::string hides a vector of byte.
+ char *buf(PyBytes_AS_STRING(pickledDataPy));// this buf can be used thanks to python documentation.
const char *inBuf(pickledData.c_str());
std::copy(inBuf,inBuf+sz,buf);
PyObject *selfMeth(PyObject_GetAttrString(dsb->getPickler(),"loads"));
PyObject *PickelizedPyObjServer::GetPyObjFromPickled(const std::vector<unsigned char>& pickledData, DataScopeServerBase *dsb)
{
std::size_t sz(pickledData.size());
- PyObject *pickledDataPy(PyString_FromStringAndSize(NULL,sz));// agy : do not use PyString_FromString because std::string hides a vector of byte.
- char *buf(PyString_AsString(pickledDataPy));// this buf can be used thanks to python documentation.
+ PyObject *pickledDataPy(PyBytes_FromStringAndSize(NULL,sz));// agy : do not use PyUnicode_FromString because std::string hides a vector of byte.
+ char *buf(PyBytes_AS_STRING(pickledDataPy));// this buf can be used thanks to python documentation.
const unsigned char *inBuf(&pickledData[0]);
std::copy(inBuf,inBuf+sz,buf);
PyObject *selfMeth(PyObject_GetAttrString(dsb->getPickler(),"loads"));
{
PyObject *args(PyTuple_New(2));
PyTuple_SetItem(args,0,obj);
- PyTuple_SetItem(args,1,PyInt_FromLong(2));// because "assert(cPickle.HIGHEST_PROTOCOL is 2)"
+ PyTuple_SetItem(args,1,PyLong_FromLong(3));// because "assert(pickle.HIGHEST_PROTOCOL is 3)"
PyObject *selfMeth(PyObject_GetAttrString(dsb->getPickler(),"dumps"));
PyObject *retPy(PyObject_CallObject(selfMeth,args));
Py_XDECREF(selfMeth);
Py_XDECREF(args);
- std::size_t sz(PyString_Size(retPy));
+ std::size_t sz(PyBytes_Size(retPy));
std::string ret(sz,'\0');
- const char *buf(PyString_AsString(retPy));
+ const char *buf(PyBytes_AS_STRING(retPy));
char *inBuf(const_cast<char *>(ret.c_str()));
for(std::size_t i=0;i<sz;i++)
inBuf[i]=buf[i];
throw Exception("PickelizedPyObjServer::setNewPyObj : trying to assign a NULL pyobject in this !");
if(obj==_self)
return ;
- if(PyList_Check(obj)==0 && PyDict_Check(obj)==0 && PyTuple_Check(obj)==0 && PyString_Check(obj)==0 && PyInt_Check(obj)==0 && PyBool_Check(obj)==0 && PyFloat_Check(obj)==0 && obj!=Py_None)
- throw Exception("PickelizedPyObjServer::setNewPyObj : Supported python types are [list,tuple,dict,str,int,bool,float,None] !");
+ if(PyList_Check(obj)==0 && PyDict_Check(obj)==0 && PyTuple_Check(obj)==0 && PyBytes_Check(obj)==0 && PyLong_Check(obj)==0 && PyBool_Check(obj)==0 && PyFloat_Check(obj)==0 && obj!=Py_None)
+ throw Exception("PickelizedPyObjServer::setNewPyObj : Supported python types are [list,tuple,dict,bytes,int,bool,float,None] !");
if(_self)
{
PyObject *selfType(PyObject_Type(_self));
def _raiseNow(strCont):
raise Exception("The method %s has been called whereas it is an interface !"%strCont)
-class WrappedType(object):
+class WrappedType(object, metaclass=abc.ABCMeta):
""" Here definition of an interface in python."""
- __metaclass__=abc.ABCMeta
@abc.abstractmethod
def ptr(self):
_raiseNow("ptr")
# Author : Anthony Geay
import SALOME
-import cPickle
+import pickle
import SALOMEWrappedStdType
class InvokatorStyle(object):
return self._var_ptr.ptr()
def local_copy(self):
- return cPickle.loads(self._var_ptr.ptr().fetchSerializedContent())
+ return pickle.loads(self._var_ptr.ptr().fetchSerializedContent())
def __str__(self):
return self.local_copy().__str__()
def assign(self,elt):
ptrCorba=self._var_ptr.ptr()
assert(isinstance(ptrCorba,SALOME._objref_PickelizedPyObjRdWrServer))
- st=cPickle.dumps(elt,cPickle.HIGHEST_PROTOCOL)
+ st=pickle.dumps(elt,pickle.HIGHEST_PROTOCOL)
ptrCorba.setSerializedContent(st)
pass
def __imul__(self,*args):
return self.local_copy().__mul__(*args)
- def __idiv__(self,*args):
- return self.local_copy().__div__(*args)
+ def __itruediv__(self,*args):
+ return self.local_copy().__truediv__(*args)
+
+ def __ifloordiv__(self,*args):
+ return self.local_copy().__floordiv__(*args)
def __add__(self,*args):
return self.local_copy().__add__(*args)
def __mul__(self,*args):
return self.local_copy().__mul__(*args)
- def __div__(self,*args):
- return self.local_copy().__div__(*args)
+ def __floordiv__(self,*args):
+ return self.local_copy().__floordiv__(*args)
+
+ def __truediv__(self,*args):
+ return self.local_copy().__truediv__(*args)
def __pow__(self,*args):
return self.local_copy().__pow__(*args)
def __imod__(self,*args):
return self.local_copy().__mod__(*args)
- def __idiv__(self,*args):
- return self.local_copy().__div__(*args)
+ def __itruediv__(self,*args):
+ return self.local_copy().__truediv__(*args)
+
+ def __ifloordiv__(self,*args):
+ return self.local_copy().__floordiv__(*args)
def __add__(self,*args):
return self.local_copy().__add__(*args)
def __mod__(self,*args):
return self.local_copy().__mod__(*args)
- def __div__(self,*args):
- return self.local_copy().__div__(*args)
-
+ def __truediv__(self,*args):
+ return self.local_copy().__truediv__(*args)
+
+ def __floordiv__(self,*args):
+ return self.local_copy().__floordiv__(*args)
+
def __pow__(self,*args):
return self.local_copy().__pow__(*args)
pass
def __call__(self,*args):
- ret=self._var_ptr.invokePythonMethodOn(self._meth,cPickle.dumps(args,cPickle.HIGHEST_PROTOCOL))
+ ret=self._var_ptr.invokePythonMethodOn(self._meth,pickle.dumps(args,pickle.HIGHEST_PROTOCOL))
return GetHandlerFromRef(ret,True)
pass
""" Returns a client that allows to handle a remote corba ref of a global var easily.
"""
assert(isinstance(objCorba,SALOME._objref_PickelizedPyObjServer))
- v=cPickle.loads(objCorba.fetchSerializedContent())
+ v=pickle.loads(objCorba.fetchSerializedContent())
if v is None:
objCorba.UnRegister()
return None
salome.salome_init()
dsm=salome.naming_service.Resolve("/DataServerManager")
d2s,isCreated=dsm.giveADataScopeCalled(scopeName)
- return GetHandlerFromRef(d2s.createRdOnlyVar(varName,cPickle.dumps(value,cPickle.HIGHEST_PROTOCOL)),False)
+ return GetHandlerFromRef(d2s.createRdOnlyVar(varName,pickle.dumps(value,pickle.HIGHEST_PROTOCOL)),False)
def CreateRdExtGlobalVar(value,varName,scopeName):
import salome
salome.salome_init()
dsm=salome.naming_service.Resolve("/DataServerManager")
d2s,isCreated=dsm.giveADataScopeCalled(scopeName)
- return GetHandlerFromRef(d2s.createRdExtVar(varName,cPickle.dumps(value,cPickle.HIGHEST_PROTOCOL)),False)
+ return GetHandlerFromRef(d2s.createRdExtVar(varName,pickle.dumps(value,pickle.HIGHEST_PROTOCOL)),False)
def GetHandlerFromName(varName,scopeName):
import salome
import SALOME
import salome
import unittest
-import cPickle
+import pickle
import gc
import time
import multiprocessing as mp
def obj2Str(obj):
- return cPickle.dumps(obj,cPickle.HIGHEST_PROTOCOL)
+ return pickle.dumps(obj,pickle.HIGHEST_PROTOCOL)
def str2Obj(strr):
- return cPickle.loads(strr)
+ return pickle.loads(strr)
def generateKey(varName,scopeName):
dsm=salome.naming_service.Resolve("/DataServerManager")
dss,isCreated=dsm.giveADataScopeTransactionCalled(scopeName)
import TestSalomeSDSHelper0
import os,subprocess
fname=os.path.splitext(TestSalomeSDSHelper0.__file__)[0]+".py"
- proc=subprocess.Popen(["python",fname],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
+ proc = subprocess.Popen(["python3", fname], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out,err=proc.communicate()
if proc.returncode!=0:
- print out
- print err
+ print(out)
+ print(err)
return proc.returncode
class SalomeSDSTest(unittest.TestCase):
#
nbProc=8
pool=mp.Pool(processes=nbProc)
- asyncResult=pool.map_async(work,[(i,varName,scopeName) for i in xrange(nbProc)])
+ asyncResult=pool.map_async(work,[(i,varName,scopeName) for i in range(nbProc)])
self.assertEqual(asyncResult.get(),nbProc*[0]) # <- the big test is here !
dsm.removeDataScope(scopeName)
import salome
import SALOME
-import cPickle
+import pickle
import gc
import SalomeSDSClt
a=d2s.createRdWrVar("str","c")
assert(a.getVarName()=="c")
#
-a.setSerializedContent(cPickle.dumps(st,cPickle.HIGHEST_PROTOCOL))
-assert(cPickle.loads(a.fetchSerializedContent())==st)
-assert(cPickle.loads(a.fetchSerializedContent())==st)
-assert(cPickle.loads(d2s.retrieveVar("c").fetchSerializedContent())==st)
+a.setSerializedContent(pickle.dumps(st,pickle.HIGHEST_PROTOCOL))
+assert(pickle.loads(a.fetchSerializedContent())==st)
+assert(pickle.loads(a.fetchSerializedContent())==st)
+assert(pickle.loads(d2s.retrieveVar("c").fetchSerializedContent())==st)
assert(isinstance(d2s.retrieveVar("c"),SALOME._objref_PickelizedPyObjRdWrServer))
assert(dsm.listScopes()==['Default','tonyy'])
dsm.createDataScope("S2")
#
sname="S7"
dsm=salome.naming_service.Resolve("/DataServerManager")
-st=cPickle.dumps([],cPickle.HIGHEST_PROTOCOL)
+st=pickle.dumps([],pickle.HIGHEST_PROTOCOL)
a=dsm.giveADataScopeCalled(sname)[0].createRdWrVar("list","a")
dsm.giveADataScopeCalled(sname)
-a.setSerializedContent(cPickle.dumps([0,],cPickle.HIGHEST_PROTOCOL))
-assert(cPickle.loads(a.fetchSerializedContent())==[0,])
+a.setSerializedContent(pickle.dumps([0,],pickle.HIGHEST_PROTOCOL))
+assert(pickle.loads(a.fetchSerializedContent())==[0,])
a.setSerializedContent(st)
-assert(cPickle.loads(a.fetchSerializedContent())==[])
-tmp=a.invokePythonMethodOn("append",cPickle.dumps((0,),cPickle.HIGHEST_PROTOCOL))
-assert(cPickle.loads(a.fetchSerializedContent())==[0])
-for i in xrange(0,1000):
- tmp=a.invokePythonMethodOn("append",cPickle.dumps((i,),cPickle.HIGHEST_PROTOCOL))
+assert(pickle.loads(a.fetchSerializedContent())==[])
+tmp=a.invokePythonMethodOn("append",pickle.dumps((0,),pickle.HIGHEST_PROTOCOL))
+assert(pickle.loads(a.fetchSerializedContent())==[0])
+for i in range(0,1000):
+ tmp=a.invokePythonMethodOn("append",pickle.dumps((i,),pickle.HIGHEST_PROTOCOL))
pass
dsm.removeDataScope(sname)
#
d2s.createRdWrVar("list","a")
a=SalomeSDSClt.GetHandlerFromRef(dsm.retriveDataScope(sname).retrieveVar("a"))
a.append(1)
-for i in xrange(1000):
+for i in range(1000):
a.append(i)
pass
assert(sum(a.local_copy())==499501)
import SALOME
-import cPickle
+import pickle
import salome
import sys
varName="a"
def obj2Str(obj):
- return cPickle.dumps(obj,cPickle.HIGHEST_PROTOCOL)
+ return pickle.dumps(obj,pickle.HIGHEST_PROTOCOL)
def str2Obj(strr):
- return cPickle.loads(strr)
+ return pickle.loads(strr)
def waitKey():
dsm=salome.naming_service.Resolve("/DataServerManager")
return str2Obj(dss.waitForMonoThrRev(wk))==[11,14,100]
if __name__=="__main__":
- sys.exit(not int(waitKey()))
+ sys.exit(not waitKey())
# 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 orbmodule
#include <iostream>
#include <fstream>
-#include <stdlib.h>
#include <SALOMEconfig.h>
#include CORBA_SERVER_HEADER(SALOMEDS_Attributes)
// purpose : Removes files listed in theFileList
//============================================================================
void SALOMEDS_Tool::RemoveTemporaryFiles(const std::string& theDirectory,
- const SALOMEDS::ListOfFileNames& theFiles,
+ const ListOfFiles& theFiles,
const bool IsDirDeleted)
{
std::string aDirName = theDirectory;
- int i, aLength = theFiles.length();
+ int i, aLength = theFiles.size();
for(i=1; i<=aLength; i++) {
std::string aFile(aDirName);
aFile += theFiles[i-1];
{
SALOMEDS::TMPFile*
PutFilesToStream(const std::string& theFromDirectory,
- const SALOMEDS::ListOfFileNames& theFiles,
- const SALOMEDS::ListOfFileNames& theFileNames,
+ const std::vector<std::string>& theFiles,
+ const std::vector<std::string>& theFileNames,
const int theNamesOnly)
{
- int i, aLength = theFiles.length();
+ int i, aLength = theFiles.size();
if(aLength == 0)
return (new SALOMEDS::TMPFile);
//Check if the file exists
if (!theNamesOnly) { // mpv 15.01.2003: if only file names must be stroed, then size of files is zero
- std::string aFullPath = aTmpDir + const_cast<char*>(theFiles[i].in());
+ std::string aFullPath = aTmpDir + theFiles[i];
if(!Exists(aFullPath)) continue;
#ifdef WIN32
std::ifstream aFile(aFullPath.c_str(), std::ios::binary);
aFileSize[i] = aFile.tellg();
aBufferSize += aFileSize[i]; //Add a space to store the file
}
- aFileNameSize[i] = strlen(theFileNames[i])+1;
+ aFileNameSize[i] = theFileNames[i].length()+1;
aBufferSize += aFileNameSize[i]; //Add a space to store the file name
aBufferSize += (theNamesOnly)?4:12; //Add 4 bytes: a length of the file name,
// 8 bytes: length of the file itself
for(i=0; i<aLength; i++) {
std::ifstream *aFile;
if (!theNamesOnly) { // mpv 15.01.2003: we don't open any file if theNamesOnly = true
- std::string aFullPath = aTmpDir + const_cast<char*>(theFiles[i].in());
+ std::string aFullPath = aTmpDir + theFiles[i];
if(!Exists(aFullPath)) continue;
#ifdef WIN32
aFile = new std::ifstream(aFullPath.c_str(), std::ios::binary);
aCurrentPos += 4;
//Copy the file name to the buffer
- memcpy((aBuffer + aCurrentPos), theFileNames[i], aFileNameSize[i]);
+ memcpy((aBuffer + aCurrentPos), theFileNames[i].c_str(), aFileNameSize[i]);
aCurrentPos += aFileNameSize[i];
if (!theNamesOnly) { // mpv 15.01.2003: we don't copy file content to the buffer if !theNamesOnly
SALOMEDS::TMPFile*
SALOMEDS_Tool::PutFilesToStream(const std::string& theFromDirectory,
- const SALOMEDS::ListOfFileNames& theFiles,
+ const ListOfFiles& theFiles,
const int theNamesOnly)
{
- SALOMEDS::ListOfFileNames aFileNames(theFiles);
+ ListOfFiles aFileNames(theFiles);
return ::PutFilesToStream(theFromDirectory,theFiles,aFileNames,theNamesOnly);
}
SALOMEDS::TMPFile*
-SALOMEDS_Tool::PutFilesToStream(const SALOMEDS::ListOfFileNames& theFiles,
- const SALOMEDS::ListOfFileNames& theFileNames)
+SALOMEDS_Tool::PutFilesToStream(const ListOfFiles& theFiles,
+ const ListOfFiles& theFileNames)
{
return ::PutFilesToStream("",theFiles,theFileNames,0);
}
// function : PutStreamToFile
// purpose : converts the stream "theStream" to the files
//============================================================================
-SALOMEDS::ListOfFileNames_var
+SALOMEDS_Tool::ListOfFiles
SALOMEDS_Tool::PutStreamToFiles(const SALOMEDS::TMPFile& theStream,
const std::string& theToDirectory,
const int theNamesOnly)
{
- SALOMEDS::ListOfFileNames_var aFiles = new SALOMEDS::ListOfFileNames;
+ ListOfFiles aFiles;
if(theStream.length() == 0)
return aFiles;
//Copy the number of files in the stream
memcpy(&aNbFiles, aBuffer, sizeof(int));
- aFiles->length(aNbFiles);
+ aFiles.reserve(aNbFiles);
for(i=0; i<aNbFiles; i++) {
aFile.close();
aCurrentPos += aFileSize;
}
- aFiles[i] = CORBA::string_dup(aFileName);
+ aFiles.push_back(CORBA::string_dup(aFileName));
delete[] aFileName;
}
}
-
#include <string>
#include <list>
+#include <vector>
+#include <stdlib.h>
// IDL headers
class TOOLSDS_EXPORT SALOMEDS_Tool
{
public:
+
+ typedef std::vector<std::string> ListOfFiles;
// Returns the unique temporary directory, that is defined in SALOME_TMP_DIR if this variable is set
// otherwise return /tmp/something/ for Unix or c:\something\ for WIN32
// Removes files which are in <theDirectory>, the files for deletion are listed in <theFiles>
// if <IsDirDeleted> is true <theDirectory> is also deleted if it is empty
static void RemoveTemporaryFiles(const std::string& theDirectory,
- const SALOMEDS::ListOfFileNames& theFiles,
+ const ListOfFiles& theFiles,
const bool IsDirDeleted);
// Converts files listed in <theFiles> which are in <theFromDirectory> into a byte sequence TMPFile
static SALOMEDS::TMPFile* PutFilesToStream(const std::string& theFromDirectory,
- const SALOMEDS::ListOfFileNames& theFiles,
+ const ListOfFiles& theFiles,
const int theNamesOnly = 0);
// Converts files listed in <theFiles> which will be named as pointed in the <theFileNames> into a byte sequence TMPFile
- static SALOMEDS::TMPFile* PutFilesToStream(const SALOMEDS::ListOfFileNames& theFiles,
- const SALOMEDS::ListOfFileNames& theFileNames);
+ static SALOMEDS::TMPFile* PutFilesToStream(const ListOfFiles& theFiles,
+ const ListOfFiles& theFileNames);
// Converts a byte sequence <theStream> to files and places them in <theToDirectory>
- static SALOMEDS::ListOfFileNames_var PutStreamToFiles(const SALOMEDS::TMPFile& theStream,
- const std::string& theToDirectory,
- const int theNamesOnly = 0);
+ static ListOfFiles PutStreamToFiles(const SALOMEDS::TMPFile& theStream,
+ const std::string& theToDirectory,
+ const int theNamesOnly = 0);
// Returns the name by the path
// for an example: if thePath = "/tmp/aaa/doc1.hdf" the function returns "doc1"
class SALOME_TestComponentPy( Engines__POA.TestComponent, SALOME_ComponentPy_i):
def Coucou(self, val):
- print "SALOME_TestComponentPy Coucou ", val
- result = "result from SALOME_TestComponentPy Coucou " + `val`
+ print("SALOME_TestComponentPy Coucou ", val)
+ result = "result from SALOME_TestComponentPy Coucou " + repr(val)
return result
def __init__(self, orb, poa, contID, containerName, instanceName, interfaceName):
notif = False
SALOME_ComponentPy_i.__init__(self, orb, poa, contID, containerName,
instanceName, interfaceName, notif)
- print "SALOME_TestComponentPy::__init__"
+ print("SALOME_TestComponentPy::__init__")
rootContext = obj._narrow(CosNaming.NamingContext)
if rootContext is None:
- print "Name Service Reference is invalid"
+ print("Name Service Reference is invalid")
sys.exit(1)
#resolve the name /Containers.dir/FactoryServerPy.object
try:
obj = rootContext.resolve(name)
-except CosNaming.NamingContext.NotFound, ex:
- print containerName , " not found in Naming Service"
+except CosNaming.NamingContext.NotFound as ex:
+ print(containerName , " not found in Naming Service")
sys.exit(1)
container = obj._narrow(Engines.Container)
-print container.getHostName()
+print(container.getHostName())
comp = container.load_impl("SalomeTestComponent","SalomeTestComponent")
-print comp._get_instanceName()
+print(comp._get_instanceName())
comp.ping()
comptest = comp._narrow(Engines.TestComponent)
if comptest is None:
- print "probleme cast"
-print comptest.Coucou(1)
+ print("probleme cast")
+print(comptest.Coucou(1))
iGenFact->load_component_Library(componenttName.c_str(),reason);
#endif
CORBA::string_free(reason);
- CORBA::Object_var obj = iGenFact->create_component_instance(componenttName.c_str(), 0);
+ CORBA::Object_var obj = iGenFact->create_component_instance(componenttName.c_str());
Engines::TestComponent_var anInstance = Engines::TestComponent::_narrow(obj);
MESSAGE("create anInstance");
SCRUTE(anInstance->instanceName());
# 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
salome_path = os.getenv("ROOT_SALOME", "")
salome_context_file = os.path.join(salome_path, "salome_context.cfg")
if not os.path.isfile(salome_context_file):
- print "File salome_context.cfg not found."
- print "Search path:" + salome_path
- print "This test needs ROOT_SALOME environment variable in order to run"
+ print("File salome_context.cfg not found.")
+ print("Search path:" + salome_path)
+ print("This test needs ROOT_SALOME environment variable in order to run")
exit(0)
config_appli_text = '''<application>
<module name="KERNEL" path="'''
kernel_path = os.getenv("KERNEL_ROOT_DIR", "")
if not os.path.isdir(kernel_path) :
- print "KERNEL_ROOT_DIR not defined"
+ print("KERNEL_ROOT_DIR not defined")
exit(0)
pass
self.salome_module = imp.load_source("SALOME", os.path.join(appli_dir, "salome"))
try:
self.salome_module.main(["start", "-t"])
- except SystemExit, e:
+ except SystemExit as e:
# There is an exit() call in salome.main. Just ignore it.
pass
ret = 0
try:
ret = self.salome_module.main(["shell", script])
- except SystemExit, e:
+ except SystemExit as e:
# return exit value
ret = e.code
return ret
def tearDown(self):
try:
self.salome_module.main(["killall"])
- except SystemExit, e:
+ except SystemExit as e:
pass
pass
pass #class TestEnvironment
Utils_ExceptHandlers.cxx
Utils_Mutex.cxx
)
- FILE(GLOB COMMON_HEADERS_HXX "${CMAKE_CURRENT_SOURCE_DIR}/*.hxx")
+ FILE(GLOB COMMON_HEADERS_HXX "${CMAKE_CURRENT_SOURCE_DIR}/*.hxx" )
ELSE()
TARGET_LINK_LIBRARIES(OpUtil ${COMMON_LIBS})
INSTALL(TARGETS OpUtil EXPORT ${PROJECT_NAME}TargetGroup DESTINATION ${SALOME_INSTALL_LIBS})
INSTALL(FILES ${COMMON_HEADERS_HXX} DESTINATION ${SALOME_INSTALL_HEADERS})
+INSTALL(FILES capsulethunk.h DESTINATION ${SALOME_INSTALL_HEADERS})
# 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 orbmodule
socket.gethostname() gives short or complete Hostname, depending on
defined aliases.
"""
- return string.split(socket.gethostname(),'.')[0]
+ hostname = socket.gethostname()
+ return hostname.split('.')[0]
class Identity:
def __init__(self,name):
--- /dev/null
+#ifndef __CAPSULETHUNK_H
+#define __CAPSULETHUNK_H
+
+#if ( (PY_VERSION_HEX < 0x02070000) \
+ || ((PY_VERSION_HEX >= 0x03000000) \
+ && (PY_VERSION_HEX < 0x03010000)) )
+
+#define __PyCapsule_GetField(capsule, field, default_value) \
+ ( PyCapsule_CheckExact(capsule) \
+ ? (((PyCObject *)capsule)->field) \
+ : (default_value) \
+ ) \
+
+#define __PyCapsule_SetField(capsule, field, value) \
+ ( PyCapsule_CheckExact(capsule) \
+ ? (((PyCObject *)capsule)->field = value), 1 \
+ : 0 \
+ ) \
+
+
+#define PyCapsule_Type PyCObject_Type
+
+#define PyCapsule_CheckExact(capsule) (PyCObject_Check(capsule))
+#define PyCapsule_IsValid(capsule, name) (PyCObject_Check(capsule))
+
+
+#define PyCapsule_New(pointer, name, destructor) \
+ (PyCObject_FromVoidPtr(pointer, destructor))
+
+
+#define PyCapsule_GetPointer(capsule, name) \
+ (PyCObject_AsVoidPtr(capsule))
+
+/* Don't call PyCObject_SetPointer here, it fails if there's a destructor */
+#define PyCapsule_SetPointer(capsule, pointer) \
+ __PyCapsule_SetField(capsule, cobject, pointer)
+
+
+#define PyCapsule_GetDestructor(capsule) \
+ __PyCapsule_GetField(capsule, destructor)
+
+#define PyCapsule_SetDestructor(capsule, dtor) \
+ __PyCapsule_SetField(capsule, destructor, dtor)
+
+
+/*
+ * Sorry, there's simply no place
+ * to store a Capsule "name" in a CObject.
+ */
+#define PyCapsule_GetName(capsule) NULL
+
+static int
+PyCapsule_SetName(PyObject *capsule, const char *unused)
+{
+ unused = unused;
+ PyErr_SetString(PyExc_NotImplementedError,
+ "can't use PyCapsule_SetName with CObjects");
+ return 1;
+}
+
+
+
+#define PyCapsule_GetContext(capsule) \
+ __PyCapsule_GetField(capsule, descr)
+
+#define PyCapsule_SetContext(capsule, context) \
+ __PyCapsule_SetField(capsule, descr, context)
+
+
+static void *
+PyCapsule_Import(const char *name, int no_block)
+{
+ PyObject *object = NULL;
+ void *return_value = NULL;
+ char *trace;
+ size_t name_length = (strlen(name) + 1) * sizeof(char);
+ char *name_dup = (char *)PyMem_MALLOC(name_length);
+
+ if (!name_dup) {
+ return NULL;
+ }
+
+ memcpy(name_dup, name, name_length);
+
+ trace = name_dup;
+ while (trace) {
+ char *dot = strchr(trace, '.');
+ if (dot) {
+ *dot++ = '\0';
+ }
+
+ if (object == NULL) {
+ if (no_block) {
+ object = PyImport_ImportModuleNoBlock(trace);
+ } else {
+ object = PyImport_ImportModule(trace);
+ if (!object) {
+ PyErr_Format(PyExc_ImportError,
+ "PyCapsule_Import could not "
+ "import module \"%s\"", trace);
+ }
+ }
+ } else {
+ PyObject *object2 = PyObject_GetAttrString(object, trace);
+ Py_DECREF(object);
+ object = object2;
+ }
+ if (!object) {
+ goto EXIT;
+ }
+
+ trace = dot;
+ }
+
+ if (PyCObject_Check(object)) {
+ PyCObject *cobject = (PyCObject *)object;
+ return_value = cobject->cobject;
+ } else {
+ PyErr_Format(PyExc_AttributeError,
+ "PyCapsule_Import \"%s\" is not valid",
+ name);
+ }
+
+EXIT:
+ Py_XDECREF(object);
+ if (name_dup) {
+ PyMem_FREE(name_dup);
+ }
+ return return_value;
+}
+
+#endif /* #if PY_VERSION_HEX < 0x02070000 */
+
+#endif /* __CAPSULETHUNK_H */