]> SALOME platform Git repositories - modules/paravis.git/commitdiff
Salome HOME
Merge from BR_PARAVIS_DEV 29Dec09 BR_FSH_DEV V5_1_main_FINAL V6_0_0
authorvsr <vsr@opencascade.com>
Tue, 29 Dec 2009 07:48:05 +0000 (07:48 +0000)
committervsr <vsr@opencascade.com>
Tue, 29 Dec 2009 07:48:05 +0000 (07:48 +0000)
66 files changed:
Makefile.am
adm_local/unix/config_files/Makefile.am
adm_local/unix/config_files/check_Med.m4 [new file with mode: 0644]
adm_local/unix/config_files/check_Med2.m4 [new file with mode: 0644]
adm_local/unix/config_files/check_ParaView.m4
adm_local/unix/config_files/check_VISU.m4 [new file with mode: 0755]
adm_local/unix/config_files/med_check_sizeof_medint.m4 [new file with mode: 0644]
build_configure
configure.ac
doc/GeneralArchitecture.odt [new file with mode: 0644]
doc/UserDocumentation.odt [new file with mode: 0644]
getwrapclasses.py [new file with mode: 0644]
idl/Makefile.am [new file with mode: 0644]
idl/PARAVIS_Gen.idl [new file with mode: 0644]
idl/PARAVIS_Gen_Types.idl [new file with mode: 0644]
idl/hints_paravis [new file with mode: 0644]
idl/pythonIDL.py [new file with mode: 0644]
idl/vtkWrapIDL.c [new file with mode: 0644]
resources/Makefile.am
resources/PARAVISCatalog.xml.in [new file with mode: 0644]
resources/SalomeApp.xml
resources/pqAppIcon16.png [new file with mode: 0644]
src/ENGINE/Makefile.am [new file with mode: 0644]
src/ENGINE/PARAVIS_Engine_i.cc [new file with mode: 0644]
src/ENGINE/PARAVIS_Engine_i.hh [new file with mode: 0644]
src/Makefile.am
src/PVGUI/Makefile.am
src/PVGUI/PARAVIS_Gen_i.cc [new file with mode: 0644]
src/PVGUI/PARAVIS_Gen_i.hh [new file with mode: 0644]
src/PVGUI/PVGUI_Module.cxx
src/PVGUI/PVGUI_Module.h
src/PVGUI/PVGUI_Module_actions.cxx
src/PVGUI/PVGUI_Module_impl.h
src/PVGUI/PVGUI_Module_widgets.cxx
src/PVGUI/PVGUI_Tools.cxx [new file with mode: 0644]
src/PVGUI/PVGUI_Tools.h [new file with mode: 0644]
src/PVGUI/PVGUI_Trace.cxx [new file with mode: 0644]
src/PVGUI/PVGUI_Trace.h [new file with mode: 0644]
src/PVGUI/PV_Events.h [new file with mode: 0644]
src/PVGUI/PV_I.h [new file with mode: 0644]
src/PVGUI/PV_Tools.cxx [new file with mode: 0644]
src/PVGUI/PV_Tools.h [new file with mode: 0644]
src/PVGUI/resources/PARAVIS_msg_en.ts
src/PV_SWIG/Makefile.am [new file with mode: 0644]
src/PV_SWIG/paravis.py [new file with mode: 0644]
src/PV_SWIG/paravisSM.py [new file with mode: 0644]
src/PV_SWIG/pvsimple.py [new file with mode: 0644]
src/PV_SWIG/servermanager.diff [new file with mode: 0644]
src/PV_SWIG/simple.diff [new file with mode: 0644]
test/MedData/BoxHexa2.med [new file with mode: 0755]
test/Pic/Information.txt [new file with mode: 0644]
test/demo0.py [new file with mode: 0755]
test/demo1.py [new file with mode: 0755]
test/demo10.py [new file with mode: 0755]
test/demo11.py [new file with mode: 0755]
test/demo12.py [new file with mode: 0755]
test/demo2.py [new file with mode: 0755]
test/demo3.py [new file with mode: 0755]
test/demo4.py [new file with mode: 0755]
test/demo5.py [new file with mode: 0755]
test/demo6.py [new file with mode: 0755]
test/demo7.py [new file with mode: 0755]
test/demo8.py [new file with mode: 0755]
test/demo9.py [new file with mode: 0755]
test/demo_14_med.py [new file with mode: 0755]
test/demo_15_med.py [new file with mode: 0755]

index 493489a89d3f9ace20651afc3638e0dcabe08371..6fe44732f19fe667ce355211b6dc1473c7764ae1 100644 (file)
@@ -28,7 +28,7 @@ ACLOCAL_AMFLAGS = -I adm_local/unix/config_files \
                   -I ${KERNEL_ROOT_DIR}/salome_adm/unix/config_files \
                   -I ${GUI_ROOT_DIR}/adm_local/unix/config_files
 
-SUBDIRS = adm_local resources src doc bin 
+SUBDIRS = idl adm_local resources src doc bin 
 
 DISTCLEANFILES = a.out aclocal.m4 configure
 
index 32784fabb31f3e2f7cc813aa8b26590ee0385bde..1cc3949b293a605c2560f7d719745d0f2022d355 100644 (file)
@@ -20,4 +20,8 @@
 include $(top_srcdir)/adm_local/unix/make_common_starter.am
 
 dist_admlocalm4_DATA = \
-       check_ParaView.m4
+       check_ParaView.m4 \
+       check_VISU.m4 \
+       check_Med.m4 \
+       check_Med2.m4 \
+       med_check_sizeof_medint.m4
diff --git a/adm_local/unix/config_files/check_Med.m4 b/adm_local/unix/config_files/check_Med.m4
new file mode 100644 (file)
index 0000000..576db97
--- /dev/null
@@ -0,0 +1,92 @@
+dnl  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
+dnl
+dnl  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
+dnl  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
+dnl
+dnl  This library is free software; you can redistribute it and/or
+dnl  modify it under the terms of the GNU Lesser General Public
+dnl  License as published by the Free Software Foundation; either
+dnl  version 2.1 of the License.
+dnl
+dnl  This library is distributed in the hope that it will be useful,
+dnl  but WITHOUT ANY WARRANTY; without even the implied warranty of
+dnl  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+dnl  Lesser General Public License for more details.
+dnl
+dnl  You should have received a copy of the GNU Lesser General Public
+dnl  License along with this library; if not, write to the Free Software
+dnl  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+dnl
+dnl  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+dnl
+# Check availability of Med binary distribution
+#
+# Author : Nicolas REJNERI (OPEN CASCADE, 2003)
+#
+
+AC_DEFUN([CHECK_MED],[
+AC_REQUIRE([AC_LINKER_OPTIONS])dnl
+AC_REQUIRE([CHECK_MED2])
+
+AC_CHECKING(for Med)
+
+Med_ok=no
+
+MED_LDFLAGS=""
+MED_CXXFLAGS=""
+
+AC_ARG_WITH(med,
+           [  --with-med=DIR root directory path of MED installation ],
+           MED_DIR="$withval",MED_DIR="")
+
+if test "x${MED_DIR}" == "x" ; then
+  AC_MSG_RESULT(for \${MED_ROOT_DIR}: ${MED_ROOT_DIR})
+# no --with-med-dir option used
+   if test "x${MED_ROOT_DIR}" != "x" ; then
+
+    # MED_ROOT_DIR environment variable defined
+      MED_DIR=${MED_ROOT_DIR}
+
+   fi
+
+fi
+
+MED_ENABLE_MULTIPR=no
+
+if test -f ${MED_DIR}/idl/salome/MED.idl ; then
+   AC_MSG_RESULT(Using Med module distribution in ${MED_DIR})
+   Med_ok=yes
+
+   if test "x$MED_ROOT_DIR" == "x" ; then
+      MED_ROOT_DIR=${MED_DIR}
+   fi
+
+   AC_SUBST(MED_ROOT_DIR)
+
+   MED_LDFLAGS=-L${MED_DIR}/lib${LIB_LOCATION_SUFFIX}/salome
+   MED_CXXFLAGS=-I${MED_DIR}/include/salome
+
+   AC_SUBST(MED_LDFLAGS)
+   AC_SUBST(MED_CXXFLAGS)
+
+   # MULTIPR
+   AC_CHECK_FILE(${MED_DIR}/include/salome/MULTIPR_Obj.hxx,
+                 ENABLE_MULTIPR=yes,
+                 ENABLE_MULTIPR=no)
+   AC_SUBST(ENABLE_MULTIPR)
+   MULTIPR_CPPFLAGS=""
+   MULTIPR_LIBS=""
+   if test "x${ENABLE_MULTIPR}" = "xyes" ; then
+      MULTIPR_CPPFLAGS="-DENABLE_MULTIPR"
+      MULTIPR_LIBS="-lMULTIPR_API"
+   fi
+   AC_SUBST(MULTIPR_CPPFLAGS)
+   AC_SUBST(MULTIPR_LIBS)
+else
+   AC_MSG_WARN("Cannot find Med module sources")
+fi
+
+AC_MSG_RESULT(for Med: $Med_ok)
+AC_MSG_RESULT(for MULTIPR Med package: $ENABLE_MULTIPR)
+
+])dnl
diff --git a/adm_local/unix/config_files/check_Med2.m4 b/adm_local/unix/config_files/check_Med2.m4
new file mode 100644 (file)
index 0000000..c5cc625
--- /dev/null
@@ -0,0 +1,200 @@
+dnl  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
+dnl
+dnl  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
+dnl  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
+dnl
+dnl  This library is free software; you can redistribute it and/or
+dnl  modify it under the terms of the GNU Lesser General Public
+dnl  License as published by the Free Software Foundation; either
+dnl  version 2.1 of the License.
+dnl
+dnl  This library is distributed in the hope that it will be useful,
+dnl  but WITHOUT ANY WARRANTY; without even the implied warranty of
+dnl  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+dnl  Lesser General Public License for more details.
+dnl
+dnl  You should have received a copy of the GNU Lesser General Public
+dnl  License along with this library; if not, write to the Free Software
+dnl  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+dnl
+dnl  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+dnl
+AC_DEFUN([CHECK_MED2],[
+AC_REQUIRE([AC_PROG_CC])dnl
+AC_REQUIRE([AC_PROG_CPP])dnl
+AC_REQUIRE([CHECK_HDF5])dnl
+AC_REQUIRE([MED_CHECK_SIZEOF_MEDINT])
+
+AC_CHECKING(for MED2)
+
+AC_ARG_WITH(med2,
+    [  --with-med2=DIR                 root directory path to med2 installation ],
+    [MED2HOME="$withval"
+      AC_MSG_RESULT("select $withval as path to med2")
+    ])
+
+AC_SUBST(MED2_INCLUDES)
+AC_SUBST(MED2_LIBS)
+AC_SUBST(MED2_MT_LIBS)
+AC_SUBST(MED_CPPFLAGS)
+
+MED2_INCLUDES=""
+MED2_LIBS=""
+MED2_MT_LIBS=""
+MED_CPPFLAGS="$DEFINED_F77INT64"
+
+med2_ok=no
+
+LOCAL_INCLUDES="$HDF5_INCLUDES"
+LOCAL_LIBS="-lmed -lmedimportcxx $HDF5_LIBS"
+
+if test -z $MED2HOME
+then
+   AC_MSG_WARN(undefined MED2HOME variable which specify med2 installation directory)
+   AC_PATH_PROG(MDUMP, mdump)
+   if test "xMDUMP" != "x" ; then
+      MED2HOME=$MDUMP
+      MED2HOME=`echo ${MED2HOME} | sed -e "s,[[^/]]*$,,;s,/$,,;s,^$,.,"`
+      MED2HOME=`echo ${MED2HOME} | sed -e "s,[[^/]]*$,,;s,/$,,;s,^$,.,"`
+   fi
+fi
+if test ! -z $MED2HOME
+then
+   LOCAL_INCLUDES="$LOCAL_INCLUDES -I$MED2HOME/include"
+   if test "x$MED2HOME" = "x/usr"
+   then
+     LOCAL_LIBS="-lmed  $LOCAL_LIBS"
+   else
+     LOCAL_LIBS="-L$MED2HOME/lib $LOCAL_LIBS"
+   fi
+fi
+
+dnl check med2 header
+
+f77int="F77INT32"
+case  $host_os in
+   irix5.* | irix6.* | osf4.* | osf5.* | linux*  )
+
+        linux64="true"
+# porting on intel processor 64 bits
+        expr "$host_os" : 'linux' >/dev/null && ( test ! x"$host_cpu" = x"x86_64" && test ! x"$host_cpu" = x"ia64" ) && linux64="false"
+       if test ! x"$linux64" = "xfalse" ; then
+         echo "$as_me:$LINENO: checking for 64bits integers size in F77/F90" >&5
+echo $ECHO_N "checking for 64bits integers size in F77/F90... $ECHO_C" >&6
+         # Check whether --enable-int64 or --disable-int64 was given.
+if test "${enable_int64+set}" = set; then
+  enableval="$enable_int64"
+
+fi;
+         case "X-$enable_int64" in
+           X-no)
+            echo "$as_me:$LINENO: result: \"disabled\"" >&5
+echo "${ECHO_T}\"disabled\"" >&6
+            SUFFIXES="_32"
+            ;;
+           *)
+            echo "$as_me:$LINENO: result: \"enabled\"" >&5
+echo "${ECHO_T}\"enabled\"" >&6
+            SUFFIXES=""
+            f77int="F77INT64"
+            ;;
+         esac
+       fi
+     ;;
+   *)
+     ;;
+esac
+
+case $host_os in
+    linux*)
+        test x"$linux64" = x"true" && \
+          MACHINE="PCLINUX64${SUFFIXES}" || \
+       MACHINE=PCLINUX
+       ;;
+    hpux*)
+       MACHINE=HP9000
+       ;;
+    aix4.*)
+       MACHINE=RS6000
+       host_os_novers=aix4.x
+       ;;
+    irix5.*)
+       MACHINE="IRIX64${SUFFIXES}"
+       host_os_novers=irix5.x
+       ;;
+    irix6.*)
+       MACHINE="IRIX64${SUFFIXES}"
+       host_os_novers=irix6.x
+       ;;
+    osf4.*)
+       MACHINE="OSF1${SUFFIXES}"
+       host_os_novers=osf4.x
+       ;;
+    osf5.*)
+       MACHINE="OSF1${SUFFIXES}"
+        host_os_novers=osf5.x
+        ;;
+    solaris2.*)
+       MACHINE=SUN4SOL2
+        host_os_novers=solaris2.x
+        ;;
+    uxpv*)
+       MACHINE=VPP5000
+        ;;
+    *)
+       MACHINE=
+        host_os_novers=$host_os
+        ;;
+esac
+
+CPPFLAGS_old="$CPPFLAGS"
+dnl we must test system : linux = -DPCLINUX
+dnl we must test system : Alpha-OSF = -DOSF1
+case $host_os in
+   linux*)
+      CPPFLAGS="$CPPFLAGS -D$MACHINE $LOCAL_INCLUDES"
+dnl      CPPFLAGS="$CPPFLAGS -DPCLINUX $LOCAL_INCLUDES"
+      ;;
+   osf*)
+      CPPFLAGS="$CPPFLAGS -DOSF1 $LOCAL_INCLUDES"
+      ;;
+esac
+AC_CHECK_HEADER(med.h,med2_ok=yes ,med2_ok=no)
+CPPFLAGS="$CPPFLAGS_old"
+
+if  test "x$med2_ok" = "xyes"
+then
+
+dnl check med2 library
+
+  LIBS_old="$LIBS"
+  LIBS="$LIBS $LOCAL_LIBS"
+  AC_CHECK_LIB(med,MEDouvrir,med2_ok=yes,med2_ok=no)
+
+  if  test "x$med2_ok" = "xyes"
+  then
+   AC_CHECK_LIB(medimportcxx,HAVE_MEDimport,med2_ok=yes,med2_ok=no)
+  fi
+  LIBS="$LIBS_old"
+fi
+
+if  test "x$med2_ok" = "xyes"
+then
+case $host_os in
+   linux*)
+      MED2_INCLUDES="-D$MACHINE $LOCAL_INCLUDES"
+dnl      MED2_INCLUDES="-DPCLINUX $LOCAL_INCLUDES"
+      ;;
+   osf*)
+      MED2_INCLUDES="-DOSF1 $LOCAL_INCLUDES"
+      ;;
+esac
+  MED2_LIBS="$LOCAL_LIBS"
+  MED2_MT_LIBS="$LOCAL_LIBS"
+fi
+
+
+AC_MSG_RESULT(for med2: $med2_ok)
+
+])dnl
index 773ff418676abf05fcbcd8474148e870e1de15f3..7ac9828dbc2d2bd8225f1cf9a98131696cc9ca99 100644 (file)
@@ -93,7 +93,7 @@ then
 fi
 
 LOCAL_INCLUDES="$OGL_INCLUDES"
-LOCAL_LIBS="-lvtksys -lvtkzlib -lvtkpng -lvtkjpeg -lvtktiff -lvtkexpat -lvtksqlite -lvtkmetaio -lvtkverdict -lvtkNetCDF -lvtkDICOMParser -lvtkfreetype -lvtkftgl -lvtkexoIIc -lvtklibxml2 -lvtkCommon -lvtkGraphics -lvtkImaging -lvtkFiltering -lvtkIO -lvtkRendering -lvtkHybrid -lvtkParallel -lvtkWidgets -lvtkClientServer -lvtkCommonCS -lvtkFilteringCS -lvtkIOCS -lvtkImagingCS -lvtkGraphicsCS -lvtkGenericFiltering -lvtkGenericFilteringCS -lvtkRenderingCS -lvtkHybridCS -lvtkParallelCS -lvtkPVCommandOptions -lKWCommon -lvtkInfovis -lvtkInfovisCS -lvtkPVServerCommon -lvtkPVServerCommonCS -lvtkCommonPythonD -lvtkFilteringPythonD -lvtkIOPythonD -lXdmf -lvtkXdmf -lvtkXdmfCS -lvtkWidgetsCS -lvtkVolumeRendering -lvtkVolumeRenderingCS -lvtkPVFilters -lvtkPVFiltersCS -lvtkViews -lvtkPVServerManagerPythonD -lvtkPVServerCommonPythonD -lvtkPVPythonInterpretor -lvtkPVServerManager -lQVTK -lpqWidgets -lQtTesting -lQtChart -lpqCore -lQtPython -lpqComponents $LXLIB -lX11 -lXt"
+LOCAL_LIBS="-lvtksys -lvtkzlib -lvtkpng -lvtkjpeg -lvtktiff -lvtkexpat -lvtksqlite -lvtkmetaio -lvtkverdict -lvtkNetCDF -lvtkDICOMParser -lvtkfreetype -lvtkftgl -lvtkexoIIc -lvtklibxml2 -lvtkCommon -lvtkGraphics -lvtkImaging -lvtkFiltering -lvtkIO -lvtkRendering -lvtkHybrid -lvtkParallel -lvtkWidgets -lvtkClientServer -lvtkCommonCS -lvtkFilteringCS -lvtkIOCS -lvtkImagingCS -lvtkGraphicsCS -lvtkGenericFiltering -lvtkGenericFilteringCS -lvtkRenderingCS -lvtkHybridCS -lvtkParallelCS -lvtkPVCommandOptions -lKWCommon -lvtkInfovis -lvtkInfovisCS -lvtkPVServerCommon -lvtkPVServerCommonCS -lvtkCommonPythonD -lvtkFilteringPythonD -lvtkIOPythonD -lXdmf -lvtkXdmf -lvtkXdmfCS -lvtkWidgetsCS -lvtkVolumeRendering -lvtkVolumeRenderingCS -lvtkPVFilters -lvtkPVFiltersCS -lvtkViews -lvtkPVServerManagerPythonD -lvtkPVServerCommonPythonD -lvtkPVPythonInterpretor -lvtkPVServerManager -lQVTK -lpqWidgets -lQtTesting -lvtkQtChart -lpqCore -lQtPython -lpqComponents -lvtkPVPython -lvtkalglib $LXLIB -lX11 -lXt"
 
 dnl VTK install dir
 if test -z $with_paraview ; then
@@ -113,25 +113,13 @@ if test "x$with_paraview" != "x" ; then
   PVHOME="$with_paraview"
 fi
 
-if test -z $PVSRCHOME ; then
   if test -z $PVHOME ; then
     AC_MSG_WARN(undefined PVHOME and PVSRCHOME variables which specify where ParaView is located)
-  else 
-    PVSRCHOME="$PVHOME/src"
-  fi
-fi
-
-if test -z $PVINSTALLHOME ; then
-  if test -z $PVHOME ; then
-    AC_MSG_WARN(undefined PVHOME and PVINSTALLHOME variables which specify where ParaView is located)
-  else
-    PVINSTALLHOME="$PVHOME/bin"
-  fi
-fi
-    
-LOCAL_INCLUDES="-I$PVSRCHOME/VTK/Common -I$PVSRCHOME/Qt/Core -I$PVSRCHOME/Qt/Components -I$PVSRCHOME/Servers/Filters -I$PVSRCHOME/Servers/Common -I$PVSRCHOME/Servers/Filters -I$PVSRCHOME/Servers/ServerManager -I$PVSRCHOME/Utilities/VTKClientServer -I$PVSRCHOME/VTK/Filtering -I$PVSRCHOME/VTK/GenericFiltering -I$PVSRCHOME/VTK/Graphics -I$PVSRCHOME/VTK/Hybrid -I$PVSRCHOME/VTK/Imaging -I$PVSRCHOME/VTK/Infovis -I$PVSRCHOME/VTK/IO -I$PVSRCHOME/VTK/Parallel -I$PVSRCHOME/VTK/Rendering -I$PVSRCHOME/VTK/Utilities -I$PVSRCHOME/VTK/Views -I$PVSRCHOME/VTK/VolumeRendering -I$PVSRCHOME/VTK/Widgets -I$PVINSTALLHOME/Qt/Core -I$PVINSTALLHOME/Qt/Components -I$PVINSTALLHOME/Utilities/VTKClientServer -I$PVINSTALLHOME/Servers/Common -I$PVINSTALLHOME/Servers/Filters -I$PVINSTALLHOME/Servers/ServerManager -I$PVINSTALLHOME/VTK -I$PVINSTALLHOME/VTK/Common -I$PVINSTALLHOME/VTK/Filtering -I$PVINSTALLHOME/VTK/GenericFiltering -I$PVINSTALLHOME/VTK/Graphics -I$PVINSTALLHOME/VTK/Hybrid -I$PVINSTALLHOME/VTK/Imaging -I$PVINSTALLHOME/VTK/Infovis -I$PVINSTALLHOME/VTK/IO -I$PVINSTALLHOME/VTK/Parallel -I$PVINSTALLHOME/VTK/Rendering -I$PVINSTALLHOME/VTK/Utilities -I$PVINSTALLHOME/VTK/Views -I$PVINSTALLHOME/VTK/VolumeRendering -I$PVINSTALLHOME/VTK/Widgets $LOCAL_INCLUDES"
+  fi  
+  
+LOCAL_INCLUDES="-I$PVHOME/include/paraview-$PVVERSION $LOCAL_INCLUDES"
 
-LOCAL_LIBS="-L$PVINSTALLHOME/bin $LOCAL_LIBS"
+LOCAL_LIBS="-L$PVHOME/lib/paraview-$PVVERSION $LOCAL_LIBS"
 
 dnl vtk headers
 CPPFLAGS_old="$CPPFLAGS"
diff --git a/adm_local/unix/config_files/check_VISU.m4 b/adm_local/unix/config_files/check_VISU.m4
new file mode 100755 (executable)
index 0000000..1fde181
--- /dev/null
@@ -0,0 +1,73 @@
+dnl  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
+dnl
+dnl  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
+dnl  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
+dnl
+dnl  This library is free software; you can redistribute it and/or
+dnl  modify it under the terms of the GNU Lesser General Public
+dnl  License as published by the Free Software Foundation; either
+dnl  version 2.1 of the License.
+dnl
+dnl  This library is distributed in the hope that it will be useful,
+dnl  but WITHOUT ANY WARRANTY; without even the implied warranty of
+dnl  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+dnl  Lesser General Public License for more details.
+dnl
+dnl  You should have received a copy of the GNU Lesser General Public
+dnl  License along with this library; if not, write to the Free Software
+dnl  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+dnl
+dnl  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+dnl
+###########################################################
+# File    : check_Visu.m4
+# Author  : Vadim SANDLER (OCN)
+# Created : 13/07/05
+# Check availability of VISU binary distribution
+###########################################################
+
+AC_DEFUN([CHECK_VISU],[
+
+AC_CHECKING(for VISU)
+
+Visu_ok=no
+
+VISU_LDFLAGS=""
+VISU_CXXFLAGS=""
+
+
+AC_ARG_WITH(visu,
+           [  --with-visu=DIR root directory path of VISU module installation ],
+           VISU_DIR="$withval",VISU_DIR="")
+
+if test "x$VISU_DIR" == "x" ; then
+   # no --with-visu-dir option used
+   if test "x$VISU_ROOT_DIR" != "x" ; then
+      # VISU_ROOT_DIR environment variable defined
+      VISU_DIR=$VISU_ROOT_DIR
+   fi
+fi
+
+if test -f ${VISU_DIR}/idl/salome/VISU_Gen.idl ; then
+   Visu_ok=yes
+   AC_MSG_RESULT(Using VISU module distribution in ${VISU_DIR})
+
+   if test "x$VISU_ROOT_DIR" == "x" ; then
+      VISU_ROOT_DIR=${VISU_DIR}
+   fi
+   AC_SUBST(VISU_ROOT_DIR)
+
+   VISU_LDFLAGS=-L${VISU_DIR}/lib${LIB_LOCATION_SUFFIX}/salome
+   VISU_CXXFLAGS=-I${VISU_DIR}/include/salome
+
+   AC_SUBST(VISU_LDFLAGS)
+   AC_SUBST(VISU_CXXFLAGS)
+
+else
+   AC_MSG_WARN("Cannot find VISU module sources")
+fi
+  
+AC_MSG_RESULT(for VISU: $Visu_ok)
+])dnl
diff --git a/adm_local/unix/config_files/med_check_sizeof_medint.m4 b/adm_local/unix/config_files/med_check_sizeof_medint.m4
new file mode 100644 (file)
index 0000000..97572a4
--- /dev/null
@@ -0,0 +1,38 @@
+dnl  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
+dnl
+dnl  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
+dnl  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
+dnl
+dnl  This library is free software; you can redistribute it and/or
+dnl  modify it under the terms of the GNU Lesser General Public
+dnl  License as published by the Free Software Foundation; either
+dnl  version 2.1 of the License.
+dnl
+dnl  This library is distributed in the hope that it will be useful,
+dnl  but WITHOUT ANY WARRANTY; without even the implied warranty of
+dnl  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+dnl  Lesser General Public License for more details.
+dnl
+dnl  You should have received a copy of the GNU Lesser General Public
+dnl  License along with this library; if not, write to the Free Software
+dnl  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+dnl
+dnl  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+dnl
+AC_DEFUN([MED_CHECK_SIZEOF_MEDINT], [
+
+  ## Guess the fortran int size
+  AC_CHECK_SIZEOF_FORTRAN(integer)
+  if test "x$ac_cv_sizeof_fortran_integer" = "x8" ; then
+     AC_CHECK_SIZEOF(long)
+     test "x$ac_cv_sizeof_long" = "x8" || AC_MSG_ERROR([Size of C type long expected to be eight bytes])
+     DEFINED_F77INT64="-DHAVE_F77INT64"
+  elif test "x$ac_cv_sizeof_fortran_integer" = "x4" ; then
+     AC_CHECK_SIZEOF(int)
+     test "x$ac_cv_sizeof_int" = "x4" || AC_MSG_ERROR([Size of C type int expected to be four bytes])
+     DEFINED_F77INT64=""
+  else
+     AC_MSG_ERROR([Size of Fortran type integer is neither four nor eigth bytes])
+  fi
+  AC_SUBST(DEFINED_F77INT64)
+])
\ No newline at end of file
index 3c8e79eb8abf85939d4ddd4dd9891968d2949c30..f6d1eca7a847e0cbe0ac017185ed58195b0660b2 100755 (executable)
@@ -48,6 +48,18 @@ cp -f ${KERNEL_ROOT_DIR}/salome_adm/unix/SALOMEconfig.h.in salome_adm/unix
 #      rm -f salome_adm/unix/config_files/${deprecated}
 #      done
 
+if test ! -f "${PVHOME}/include/paraview-${PVVERSION}/vtkSMProxyManager.h"; then
+    echo "failed : PVHOME variable is not correct !"
+    exit
+fi
+
+`pvpython getwrapclasses.py`
+
+#file hints contain the size of returned arrays
+cp -f ${PVHOME}/lib/paraview-${PVVERSION}/hints idl/hints
+if [ -f idl/hints_paravis ]; then
+    cat idl/hints_paravis >> idl/hints
+fi
 
 # ____________________________________________________________________
 # aclocal creates the aclocal.m4 file from the standard macro and the
index 7e5a1b5ce1d857768e88ef215652319cfc717098..1c053a3012c43396ac269f4ddbaafdc91daa73fc 100644 (file)
@@ -19,7 +19,7 @@ AC_INIT([PARAVIS - SALOME GUI for ParaView], [0.1.0], [webmaster.salome@opencasc
 AC_CONFIG_AUX_DIR(salome_adm/unix/config_files)
 AC_CANONICAL_HOST
 AC_CANONICAL_TARGET
-AM_INIT_AUTOMAKE
+AM_INIT_AUTOMAKE([-Wno-portability])
 
 XVERSION=`echo $VERSION | awk -F. '{printf("0x%02x%02x%02x",$1,$2,$3)}'`
 AC_SUBST(XVERSION)
@@ -197,13 +197,13 @@ dnl echo
 
 dnl CHECK_JAVA
 
-#echo
-#echo ---------------------------------------------
-#echo testing swig
-#echo ---------------------------------------------
-#echo
-#
-#CHECK_SWIG
+echo
+echo ---------------------------------------------
+echo testing swig
+echo ---------------------------------------------
+echo
+
+CHECK_SWIG
 
 echo
 echo ---------------------------------------------
@@ -213,6 +213,35 @@ echo
 
 ENABLE_PTHREADS
 
+echo
+echo ---------------------------------------------
+echo testing omniORB
+echo ---------------------------------------------
+echo
+
+CHECK_OMNIORB
+
+dnl echo
+dnl echo ---------------------------------------------
+dnl echo testing mico
+dnl echo ---------------------------------------------
+dnl echo
+
+dnl CHECK_MICO
+
+echo
+echo ---------------------------------------------
+echo default ORB : omniORB
+echo ---------------------------------------------
+echo
+
+DEFAULT_ORB=omniORB
+CHECK_CORBA
+
+AC_SUBST_FILE(CORBA)
+corba=make_$ORB
+CORBA=adm_local/unix/$corba
+
 echo
 echo ---------------------------------------------
 echo testing openGL
@@ -277,6 +306,24 @@ echo
 
 CHECK_SALOME_GUI
 
+echo
+echo ---------------------------------------------
+echo testing VISU
+echo ---------------------------------------------
+echo
+
+CHECK_VISU
+
+echo
+echo ---------------------------------------------
+echo testing MED
+echo ---------------------------------------------
+echo
+
+CHECK_MED
+
+AM_CONDITIONAL(MED_ENABLE_MULTIPR, [test "$ENABLE_MULTIPR" = yes])
+
 echo
 echo ---------------------------------------------
 echo Summary
@@ -284,7 +331,7 @@ echo ---------------------------------------------
 echo
 
 echo Configure
-variables="cc_ok lex_yacc_ok python_ok threads_ok OpenGL_ok qt_ok hdf5_ok paraview_ok occ_ok doxygen_ok graphviz_ok Kernel_ok SalomeGUI_ok"
+variables="cc_ok lex_yacc_ok python_ok swig_ok threads_ok OpenGL_ok qt_ok hdf5_ok paraview_ok omniORB_ok occ_ok doxygen_ok graphviz_ok Kernel_ok SalomeGUI_ok Visu_ok Med_ok"
 
 for var in $variables
 do
@@ -307,7 +354,7 @@ if test "$HAS_CMAKE" = "yes"; then
     mkdir -p ${ROOT_BUILDDIR}/src/Plugins
   fi
   cd ${ROOT_BUILDDIR}/src/Plugins
-  cmake -D ParaView_DIR=${PVINSTALLHOME} -D CMAKE_BUILD_TYPE=Debug -D CMAKE_INSTALL_PREFIX=${PARAVIS_ROOT_DIR}/lib/salome ${ROOT_SRCDIR}/src/Plugins
+  cmake -D ParaView_DIR=${PVHOME}/lib/paraview-${PVVERSION} -D CMAKE_BUILD_TYPE=Debug -D CMAKE_INSTALL_PREFIX=${prefix}/lib/paraview ${ROOT_SRCDIR}/src/Plugins
   cd $curdir
 fi
   
@@ -344,9 +391,13 @@ AC_OUTPUT([ \
   ./doc/salome/Makefile \
   ./doc/salome/gui/Makefile \
   ./doc/salome/gui/doxyfile \
+  ./idl/Makefile \
   ./src/Makefile \
   ./src/PVGUI/Makefile \
+  ./src/PV_SWIG/Makefile \
+  ./src/ENGINE/Makefile \
   ./resources/Makefile \
+  ./resources/PARAVISCatalog.xml \
   ./PARAVIS_version.h \
   Makefile \
 ])
diff --git a/doc/GeneralArchitecture.odt b/doc/GeneralArchitecture.odt
new file mode 100644 (file)
index 0000000..3224fb6
Binary files /dev/null and b/doc/GeneralArchitecture.odt differ
diff --git a/doc/UserDocumentation.odt b/doc/UserDocumentation.odt
new file mode 100644 (file)
index 0000000..46743f7
Binary files /dev/null and b/doc/UserDocumentation.odt differ
diff --git a/getwrapclasses.py b/getwrapclasses.py
new file mode 100644 (file)
index 0000000..db2969d
--- /dev/null
@@ -0,0 +1,178 @@
+import paraview, os
+import string
+import re
+
+classeslistsm = []
+classeslistvtk = []
+
+if os.name == "posix":
+    from libvtkPVServerCommonPython import *
+    from libvtkPVServerManagerPython import *
+else:
+    from vtkPVServerCommonPython import *
+    from vtkPVServerManagerPython import *
+
+l1 = dir()
+for a in l1:
+    if a.startswith("vtk") and (len(a) > 3):
+        classeslistsm.append(a)
+        
+from paraview.vtk import *
+l2 = dir()
+
+for a in l2:
+    if (a not in l1) and a.startswith("vtk"):
+        classeslistvtk.append(a)
+
+pvhome = os.environ.get('PVHOME')
+pvversion = os.environ.get('PVVERSION')
+wrap_dir="include/paraview-"+pvversion
+
+dic=dict();
+pv_classes_new=classeslistsm
+while len(pv_classes_new):
+    pv_classes_cur=pv_classes_new
+    pv_classes_new=[]
+    for c in pv_classes_cur:
+        filename=pvhome+"/"+wrap_dir+"/"+c+".h"
+        if os.path.isfile(filename):
+            c_new=[]
+            f=open(filename)
+            for line in f:
+                if re.match('\s*/',line) is None:
+                    if re.match('\s*public\s*:',line):
+                        continue
+
+                    m=re.match('\s*class\s+(vtk\w+)\s*;',line)
+                    if m is not None:
+                        cn=m.group(1)
+                        if cn not in dic.keys() and cn not in pv_classes_new and cn in classeslistvtk:
+                            pv_classes_new.append(cn)
+                            continue
+
+                    m=re.match('\s*struct\s+(vtk\w+)\s*;',line)
+                    if m is not None:
+                        cn=m.group(1)
+                        if cn not in dic.keys() and cn not in pv_classes_new and cn in classeslistvtk:
+                            pv_classes_new.append(cn)
+                            continue
+
+                    m=re.match('\s*#include\s+"(vtk\w+)\.h"',line)
+                    if m is not None:
+                        cn=m.group(1)
+                        if cn not in dic.keys() and cn not in pv_classes_new and cn in classeslistvtk:
+                            pv_classes_new.append(cn)
+                            continue
+
+                    cm=re.findall('public\s+(vtk\w+)',line)
+                    if len(cm) == 0:
+                        continue
+                    for cn in cm:
+                        if cn not in dic.keys() and cn not in pv_classes_new:
+                            pv_classes_new.append(cn)
+                        if cn not in c_new:
+                            c_new.append(cn)
+            f.close()
+            dic[c]=[0, c_new]
+
+pv_classes_sort=[]
+
+def collect_dic(cc):
+    ret=[]
+    for c in cc:
+        if len(dic[c][1]) and dic[c][0] == 0:
+             ret+=collect_dic(dic[c][1])
+        if dic[c][0] == 0:
+            ret.append(c)
+            dic[c][0]=1
+    return ret
+
+pv_classes_sort=collect_dic(dic.keys())
+
+awidl='WRAP_IDL = '
+awsk='WRAP_SK_FILES = '
+awhh='WRAP_IDL_I_HH = '
+awcc='WRAP_IDL_I_CC = '
+
+fprefix='PARAVIS_Gen_'
+fidl='.idl'
+fsk='SK.cc'
+fhh='_i.hh'
+fcc='_i.cc'
+
+idl_am=open('idl/wrap.am','w')
+idl_i_am=open('src/PVGUI/wrap.am','w')
+
+wrap_h=open('idl/vtkWrapIDL.h','w')
+wrap_h.write('const char* wrapped_classes[] = {\n')
+
+wrap_cxx=open('src/PVGUI/PARAVIS_CreateClass.cxx','w')
+wrap_cxx.write('#include <iostream>\n')
+wrap_cxx.write('#include <QString>\n')
+wrap_cxx.write('#include "PARAVIS_Gen_i.hh"\n')
+
+for c in pv_classes_sort:
+    widl=fprefix+c+fidl
+    wsk=fprefix+c+fsk
+    whh=fprefix+c+fhh
+    wcc=fprefix+c+fcc
+    awidl+=' ' + widl
+    awsk+=' ' + wsk
+    awhh+=' ' + whh
+    awcc+=' ' + wcc
+
+    idl_am.write(widl+': vtkWrapIDL')
+    for cc in dic[c][1]:
+        idl_am.write(' '+fprefix+cc+fidl)
+    idl_am.write('\n')
+    idl_am.write('\t@./vtkWrapIDL '+pvhome+'/'+wrap_dir+'/'+c+'.h $(top_srcdir)/idl/hints 0 $@\n')
+    idl_am.write('\n')
+
+
+    idl_i_am.write(whh+': vtkWrapIDL_HH')
+    for cc in dic[c][1]:
+        idl_i_am.write(' '+fprefix+cc+fhh)
+    idl_i_am.write('\n')
+    idl_i_am.write('\t@./vtkWrapIDL_HH '+pvhome+'/'+wrap_dir+'/'+c+'.h $(top_srcdir)/idl/hints 0 $@\n')
+    idl_i_am.write('\n')
+
+    idl_i_am.write(wcc+': vtkWrapIDL_CC $(WRAP_IDL_I_HH)')
+    for cc in dic[c][1]:
+        idl_i_am.write(' '+fprefix+cc+fcc)
+    idl_i_am.write('\n')
+    idl_i_am.write('\t@./vtkWrapIDL_CC '+pvhome+'/'+wrap_dir+'/'+c+'.h $(top_srcdir)/idl/hints 0 $@\n')
+    idl_i_am.write('\n')
+
+    wrap_h.write('"'+c+'",\n')
+
+    wrap_cxx.write('#include "'+fprefix+c+fhh+'"\n')
+
+idl_am.write(awidl+'\n')
+idl_am.write('\n')
+idl_am.write(awsk+'\n')
+
+idl_i_am.write(awhh+'\n')
+idl_i_am.write('\n')
+idl_i_am.write(awcc+'\n')
+idl_i_am.write('\n')
+idl_i_am.write('BUILT_SOURCES = $(WRAP_IDL_I_HH) $(WRAP_IDL_I_CC)\n')
+
+wrap_h.write('""\n};\n')
+
+wrap_cxx.write('\n')
+wrap_cxx.write('PARAVIS::PARAVIS_Base_i* CreateInstance(::vtkObjectBase* Inst, const QString& theClassName)\n')
+wrap_cxx.write('{\n')
+for i in range(len(pv_classes_sort)-1,-1,-1):
+    c=pv_classes_sort[i]
+    wrap_cxx.write('    if(theClassName == "'+c+'" || (Inst != NULL && Inst->IsA("'+c+'")))\n')
+    wrap_cxx.write('      return new PARAVIS::'+c+'_i();\n')
+wrap_cxx.write('\n')
+wrap_cxx.write('    cerr << "The class " << theClassName.toStdString() << " is not created!" << endl;\n')
+wrap_cxx.write('    return new PARAVIS::PARAVIS_Base_i();\n')
+wrap_cxx.write('}\n')
+
+idl_am.close()
+idl_i_am.close()
+wrap_h.close()
+wrap_cxx.close()
+
diff --git a/idl/Makefile.am b/idl/Makefile.am
new file mode 100644 (file)
index 0000000..875b937
--- /dev/null
@@ -0,0 +1,104 @@
+#  Copyright (C) 2007-2008  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.
+#
+#  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
+#
+# This Makefile is responsible of generating the client and server
+# implementation of IDL interfaces for both C++ and python usage.
+# The building process of the C++ files is in charge of each source
+# package and then is not manage here.
+#
+include $(top_srcdir)/adm_local/unix/make_common_starter.am
+
+#Executable
+bin_PROGRAMS = vtkWrapIDL 
+
+dist_vtkWrapIDL_SOURCES = ${PVHOME}/src/vtkParse.tab.c vtkWrapIDL.c
+
+vtkWrapIDL_CPPFLAGS = \
+       ${PARAVIEW_INCLUDES}
+
+include $(srcdir)/wrap.am
+
+BASEIDL_FILES = PARAVIS_Gen_Types.idl PARAVIS_Gen.idl 
+BASEIDL_SK_FILES= PARAVIS_Gen_TypesSK.cc PARAVIS_GenSK.cc
+
+# This variable defines the files to be installed
+dist_salomeidl_DATA = $(BASEIDL_FILES) $(WRAP_IDL)
+
+# PARAVIS idl common library
+lib_LTLIBRARIES = libSalomeIDLPARAVIS.la
+
+# Sources built from idl files
+nodist_libSalomeIDLPARAVIS_la_SOURCES = $(BASEIDL_SK_FILES) $(WRAP_SK_FILES)
+
+# header files must be exported: other modules have to use this library
+nodist_salomeinclude_HEADERS = $(BASEIDL_FILES:%.idl=%.hh) $(WRAP_IDL:%.idl=%.hh)
+
+libSalomeIDLPARAVIS_la_CPPFLAGS =                      \
+       -I$(top_builddir)/salome_adm/unix       \
+       -I$(top_builddir)/idl                   \
+       @CORBA_CXXFLAGS@ @CORBA_INCLUDES@ @KERNEL_CXXFLAGS@ 
+libSalomeIDLPARAVIS_la_LDFLAGS = -no-undefined -version-info=0:0:0
+libSalomeIDLPARAVIS_la_LIBADD  = @CORBA_LIBS@ 
+
+# These variables defines the building process of CORBA files
+OMNIORB_IDL         = @OMNIORB_IDL@
+OMNIORB_IDLCXXFLAGS = @OMNIORB_IDLCXXFLAGS@
+OMNIORB_IDLPYFLAGS  = @OMNIORB_IDLPYFLAGS@ -I$(KERNEL_ROOT_DIR)/idl/salome 
+IDLCXXFLAGS = -bcxx @IDLCXXFLAGS@ -I$(srcdir) -I$(KERNEL_ROOT_DIR)/idl/salome -I$(top_builddir)/salome_adm/unix
+IDLPYFLAGS  = -bpythonIDL -p$(srcdir) -I$(srcdir) -I$(KERNEL_ROOT_DIR)/idl/salome
+
+# potential problem on parallel make on the following - multiple outputs
+SUFFIXES = .idl .hh SK.cc
+.idlSK.cc:
+       $(OMNIORB_IDL) $(IDLCXXFLAGS) $(OMNIORB_IDLCXXFLAGS) $<
+.idl.hh:
+       $(OMNIORB_IDL) $(IDLCXXFLAGS) $(OMNIORB_IDLCXXFLAGS) $<
+
+install-exec-local: $(BASEIDL_FILES:%=$(top_srcdir)/idl/%) $(WRAP_IDL)
+       $(INSTALL) -d  $(DESTDIR)$(salomepythondir)
+       ls $^ | while read file; do \
+         $(OMNIORB_IDL) $(IDLPYFLAGS) -C$(DESTDIR)$(salomepythondir) $$file ; \
+       done
+
+# uninstall-local removes too much, but it works in distcheck
+uninstall-local:
+       rm -rf $(DESTDIR)$(salomepythondir)/*
+
+mostlyclean-local: clean-idls
+
+clean-idls:
+       @find . \( -name "*.hh" -or -name "*.cc" -or -name ".depidl" -or -name "*.idl" \) -exec rm -f {} \;
+
+# we use cpp to generate dependencies between idl files.
+# option x c tells the preprocessor to consider idl as a c file.
+# if an idl is modified, all idl dependencies are rebuilt
+
+.depidl: $(BASEIDL_FILES)
+       @echo "" > $@
+       @for dep in $^ dummy; do \
+         if [ $$dep != "dummy" ]; then \
+           echo Building dependencies for $$dep; \
+           $(CPP) $(C_DEPEND_FLAG) $(C_WRAP_IDL_FLAG) -x c -I$(srcdir) -I$(KERNEL_ROOT_DIR)/idl/salome $$dep 2>/dev/null | \
+           sed 's/\.o/\SK.cc/' >>$@; \
+         fi; \
+       done ;
+
+-include .depidl
diff --git a/idl/PARAVIS_Gen.idl b/idl/PARAVIS_Gen.idl
new file mode 100644 (file)
index 0000000..ed39460
--- /dev/null
@@ -0,0 +1,120 @@
+//  Copyright (C) 2007-2008  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.
+//
+//  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   : PARAVIS_Gen.idl
+//  Author : Vitaly Smetannikov
+//
+
+/*! \file PARAVIS_Gen.idl This file conatins a set of interfaces of the %PARAVIS module.
+ *     This module provides access to PARAVIEW functionality integrated to %SALOME application.
+ */
+
+#ifndef __PARAVIS_GEN__
+#define __PARAVIS_GEN__
+
+#include "SALOME_Exception.idl"
+#include "SALOME_GenericObj.idl"
+#include "SALOME_Component.idl"
+#include "SALOMEDS.idl"
+#include "PARAVIS_Gen_Types.idl"
+
+/*!
+  The main package of interfaces of the module %PARAVIS.
+*/
+module PARAVIS {
+
+  interface vtkObject;
+  interface vtkSMObject;
+  interface vtkProcessModule;
+  interface vtkPVPythonModule;
+
+  /*!
+   * \brief Base class for all PARAVIS container(wrapper) classes
+   */
+  interface PARAVIS_Base {
+    boolean IsSame(in PARAVIS_Base theOther);
+  };
+    
+
+  /*!
+   * \brief The main interface class for PARAVIS server. 
+   * Instantiation of this class has to be done before access to any other PARAVIS interfaces
+   */
+  interface PARAVIS_Gen : Engines::Component, SALOMEDS::Driver
+  {
+    /*!
+     * \brief Returns IOR of the current object.
+     */
+    string GetIOR();
+
+    /*!
+     * \brief Import file to PARAVIS module. 
+     * File can be of any type supported by Paraview and installed plug-ins.
+     */
+    void ImportFile(in string theFileName);
+
+
+    /*!
+     * Returns trace string if trace is activated for current session. 
+     * Otherwise it returns empty string.
+     */
+    string GetTrace();
+
+    /*!
+     * \brief Save trace sting to a disk file.
+     * \param theFileName - name of file.
+     */
+    void SaveTrace(in string theFileName);
+
+    /*!
+     * \brief Returns list of names of extracted Paraview and VTK classes
+     */
+    string_array GetClassesList();
+
+    /*!
+     * \brief Returns container class for the requested Paraview class
+     */
+    PARAVIS_Base CreateClass(in string theClassName);
+
+    /*!
+     * Returns parameters of current (usually built-in) connection which is active in GUI (Paraview client).
+     * \param theId - connection ID
+     * \param theDHost - name of data host
+     * \param theDPort - number of data port
+     * \param theRHost - name of representation host
+     * \param theRPort - number of representation port
+     * \param theReversed - returns 1 or 0 depending on server resource scheme
+     */
+    void GetConnectionParameters(out long theId, out string theDHost, out long theDPort, 
+                                 out string theRHost, out long theRPort, out long theReversed);
+
+    /*! 
+     * \brief Activates GUI of PARAVIS module. If module is active then do nothing.
+     * GUI must be active before call of any server manager API function.
+     * This function is called on activation paravis python module.
+     */
+    void ActivateModule();
+
+  };
+
+};
+
+#endif
diff --git a/idl/PARAVIS_Gen_Types.idl b/idl/PARAVIS_Gen_Types.idl
new file mode 100644 (file)
index 0000000..132fe4f
--- /dev/null
@@ -0,0 +1,48 @@
+//  Copyright (C) 2007-2008  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.
+//
+//  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   : PARAVIS_Gen.idl
+//  Author : Vladimir Turin
+//
+
+/*! \file PARAVIS_Gen_Types.idl This file conatins a set of type declarations of the %PARAVIS module.
+ *     This module provides access to PARAVIEW functionality integrated to %SALOME application.
+ */
+
+
+#ifndef __PARAVIS_GEN_TYPES__
+#define __PARAVIS_GEN_TYPES__
+
+#/*!
+  Definition of collection classes for %PARAVIS module.
+*/
+module PARAVIS {
+
+  typedef string function;
+  typedef sequence<string> string_array;
+  typedef sequence<short> short_array;
+  typedef sequence<long> long_array;
+  typedef sequence<float> float_array;
+  typedef sequence<double> double_array;
+
+};
+
+#endif
diff --git a/idl/hints_paravis b/idl/hints_paravis
new file mode 100644 (file)
index 0000000..dc3089f
--- /dev/null
@@ -0,0 +1 @@
+vtkPVArrayInformation        GetComponentRange      307  2
\ No newline at end of file
diff --git a/idl/pythonIDL.py b/idl/pythonIDL.py
new file mode 100644 (file)
index 0000000..4954d24
--- /dev/null
@@ -0,0 +1,2848 @@
+# -*- python -*-
+#                           Package   : omniidl
+# python.py                 Created on: 1999/10/29
+#                          Author    : Duncan Grisby (dpg1)
+#
+#    Copyright (C) 1999 AT&T Laboratories Cambridge
+#
+#  This file is part of omniidl.
+#
+#  omniidl is free software; you can redistribute it and/or modify it
+#  under the terms of the GNU General Public License as published by
+#  the Free Software Foundation; either version 2 of the License, or
+#  (at your option) any later version.
+#
+#  This program 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
+#  General Public License for more details.
+#
+#  You should have received a copy of the GNU General Public License
+#  along with this program; if not, write to the Free Software
+#  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
+#  02111-1307, USA.
+#
+# Description:
+#   
+#   Back-end for Python
+
+# $Id$
+# $Log$
+# Revision 1.1.2.4  2009-11-18 15:56:23  vtn
+# Trace support
+#
+# Revision 1.1.2.3  2009-11-17 12:15:43  vsv
+# *** empty log message ***
+#
+# Revision 1.1.2.2  2009-11-05 14:57:23  vtn
+# Added return array support.
+#
+# Revision 1.1.2.1  2009-11-03 13:14:05  vtn
+# Added pathonIDL back-end for omniidl.
+#
+# Revision 1.33.2.13  2006/10/11 17:44:14  dgrisby
+# None is not a keyword, but it cannot be assigned to.
+#
+# Revision 1.33.2.12  2006/09/29 16:48:03  dgrisby
+# Stub changes broke use of package prefix. Thanks Teemu Torma.
+#
+# Revision 1.33.2.11  2006/09/07 15:28:57  dgrisby
+# Remove obsolete check for presence of omniORB.StructBase.
+#
+# Revision 1.33.2.10  2006/06/21 14:46:26  dgrisby
+# Invalid generated code for structs nested inside valuetypes.
+#
+# Revision 1.33.2.9  2006/01/19 17:28:44  dgrisby
+# Merge from omnipy2_develop.
+#
+# Revision 1.33.2.8  2006/01/18 19:25:13  dgrisby
+# Bug inheriting a valuetype from a typedef.
+#
+# Revision 1.33.2.7  2005/07/29 11:21:36  dgrisby
+# Fix long-standing problem with module re-opening by #included files.
+#
+# Revision 1.33.2.6  2005/01/07 00:22:34  dgrisby
+# Big merge from omnipy2_develop.
+#
+# Revision 1.33.2.5  2004/03/24 22:28:50  dgrisby
+# TypeCodes / truncation for inherited state members were broken.
+#
+# Revision 1.33.2.4  2004/02/16 10:14:18  dgrisby
+# Use stream based copy for local calls.
+#
+# Revision 1.33.2.3  2003/07/10 22:13:25  dgrisby
+# Abstract interface support.
+#
+# Revision 1.33.2.2  2003/05/20 17:10:24  dgrisby
+# Preliminary valuetype support.
+#
+# Revision 1.33.2.1  2003/03/23 21:51:56  dgrisby
+# New omnipy3_develop branch.
+#
+# Revision 1.29.2.14  2002/11/25 21:31:09  dgrisby
+# Friendly error messages with file errors, remove code to kill POA
+# modules from pre-1.0.
+#
+# Revision 1.29.2.13  2002/07/04 13:14:52  dgrisby
+# Bug with string escapes in Windows filenames.
+#
+# Revision 1.29.2.12  2002/05/27 01:02:37  dgrisby
+# Fix bug with scope lookup in generated code. Fix TypeCode clean-up bug.
+#
+# Revision 1.29.2.11  2002/01/18 17:41:17  dpg1
+# Support for "docstrings" in IDL.
+#
+# Revision 1.29.2.10  2002/01/18 15:49:45  dpg1
+# Context support. New system exception construction. Fix None call problem.
+#
+# Revision 1.29.2.9  2001/12/04 12:17:08  dpg1
+# Incorrect generated code for fixed constants.
+#
+# Revision 1.29.2.8  2001/08/29 11:57:16  dpg1
+# Const fixes.
+#
+# Revision 1.29.2.7  2001/06/15 10:59:26  dpg1
+# Apply fixes from omnipy1_develop.
+#
+# Revision 1.29.2.6  2001/06/13 11:29:04  dpg1
+# Proper omniidl support for wchar/wstring constants.
+#
+# Revision 1.29.2.5  2001/05/10 15:16:03  dpg1
+# Big update to support new omniORB 4 internals.
+#
+# Revision 1.29.2.4  2001/04/09 15:22:16  dpg1
+# Fixed point support.
+#
+# Revision 1.29.2.3  2000/11/22 14:43:58  dpg1
+# Support code set conversion and wchar/wstring.
+#
+# Revision 1.29.2.2  2000/11/01 15:29:01  dpg1
+# Support for forward-declared structs and unions
+# RepoIds in indirections are now resolved at the time of use
+#
+# Revision 1.29.2.1  2000/10/13 13:55:30  dpg1
+# Initial support for omniORB 4.
+#
+# Revision 1.29  2000/10/02 17:34:58  dpg1
+# Merge for 1.2 release
+#
+# Revision 1.27.2.3  2000/08/22 11:52:28  dpg1
+# Generate inherited classes for typedef to struct/union.
+#
+# Revision 1.27.2.2  2000/08/07 09:19:24  dpg1
+# Long long support
+#
+# Revision 1.27.2.1  2000/07/18 15:31:29  dpg1
+# Bug with inheritance from typedef
+#
+# Revision 1.27  2000/07/12 14:32:13  dpg1
+# New no_package option to omniidl backend
+#
+# Revision 1.26  2000/06/28 12:47:48  dpg1
+# Proper error messages for unsupported IDL constructs.
+#
+# Revision 1.25  2000/06/27 15:01:48  dpg1
+# Change from POA_M to M__POA mapping.
+# Global module only built if necessary.
+#
+# Revision 1.24  2000/03/29 10:15:47  dpg1
+# Exceptions now more closely follow the interface of
+# exceptions.Exception.
+#
+# Revision 1.23  2000/03/17 12:28:09  dpg1
+# Comma missing in nested union descriptor.
+#
+# Revision 1.22  2000/03/03 17:41:28  dpg1
+# Major reorganisation to support omniORB 3.0 as well as 2.8.
+#
+# Revision 1.21  2000/02/23 10:20:52  dpg1
+# Bug in descriptors for single-item enums.
+#
+# Revision 1.20  2000/01/04 15:29:41  dpg1
+# Fixes to modules generated within a package.
+#
+# Revision 1.19  1999/12/21 16:06:15  dpg1
+# DOH!  global= not module= !
+#
+# Revision 1.18  1999/12/21 16:05:11  dpg1
+# New module= option.
+#
+# Revision 1.17  1999/12/17 11:39:52  dpg1
+# New arguments to put modules and stubs in a specified package.
+#
+# Revision 1.16  1999/12/15 11:32:42  dpg1
+# -Wbinline option added.
+#
+# Revision 1.15  1999/12/09 14:12:55  dpg1
+# invokeOp() calls now on a single line. typedef now generates a class
+# to be passed to CORBA.id().
+#
+# Revision 1.14  1999/12/07 15:35:14  dpg1
+# Bug in currentScope handling.
+#
+# Revision 1.13  1999/11/30 10:41:20  dpg1
+# Back-ends can now have their own usage string.
+#
+# Revision 1.12  1999/11/25 11:49:31  dpg1
+# Minor version number bumped since server-side _is_a() required an
+# incompatible change.
+#
+# Revision 1.11  1999/11/25 11:21:36  dpg1
+# Proper support for server-side _is_a().
+#
+# Revision 1.10  1999/11/19 11:03:49  dpg1
+# Extremely important spelling correction in a comment. :-)
+#
+# Revision 1.9  1999/11/12 15:53:48  dpg1
+# New functions omniORB.importIDL() and omniORB.importIDLString().
+#
+# Revision 1.8  1999/11/11 15:55:29  dpg1
+# Python back-end interface now supports valuetype declarations.
+# Back-ends still don't support them, though.
+#
+# Revision 1.7  1999/11/10 16:08:22  dpg1
+# Some types weren't registered properly.
+#
+# Revision 1.6  1999/11/04 11:46:12  dpg1
+# Now uses our own version of the GNU C preprocessor.
+#
+# Revision 1.5  1999/11/02 12:17:26  dpg1
+# Top-level module name now has a prefix of _0_ to avoid clashes with
+# names of nested declarations.
+#
+# Revision 1.4  1999/11/02 10:54:01  dpg1
+# Two small bugs in union generation.
+#
+# Revision 1.3  1999/11/02 10:01:46  dpg1
+# Minor fixes.
+#
+# Revision 1.2  1999/11/01 20:19:55  dpg1
+# Support for union switch types declared inside the switch statement.
+#
+# Revision 1.1  1999/11/01 16:40:11  dpg1
+# First revision with new front-end.
+#
+
+"""omniORB Python bindings"""
+
+from omniidl import idlast, idltype, idlutil, idlvisitor, output, main
+import sys, string, types, os.path, keyword
+
+cpp_args = ["-D__OMNIIDL_PYTHON__"]
+usage_string = """\
+  -Wbstdout       Send generated stubs to stdout rather than a file
+  -Wbinline       Output stubs for #included files in line with the main file
+  -Wbfactories    Register value factories for all valuetypes
+  -Wbpackage=p    Put both Python modules and stub files in package p
+  -Wbmodules=p    Put Python modules in package p
+  -Wbstubs=p      Put stub files in package p
+  -Wbextern=f:p   Assume Python stub file for file f is in package p.
+  -Wbglobal=g     Module to use for global IDL scope (default _GlobalIDL)"""
+
+#""" Uncomment this line to get syntax highlighting on the output strings
+
+# Output strings
+
+pymodule_template = """\
+# DO NOT EDIT THIS FILE!
+#
+# Python module @module@ generated by omniidl
+
+import omniORB
+omniORB.updateModule("@package@@module@")
+
+# ** 1. Stub files contributing to this module
+
+# ** 2. Sub-modules
+
+# ** 3. End"""
+
+file_start = """\
+# Python stubs generated by omniidl from @filename@
+
+import omniORB, _omnipy
+from types import *
+from omniORB import CORBA, PortableServer
+_0_CORBA = CORBA
+
+_omnipy.checkVersion(3,0, __file__)
+"""
+
+file_end = """\
+_exported_modules = ( @export_string@)
+
+# The end."""
+
+module_start = """
+#
+# Start of module "@sname@"
+#
+__name__ = "@package@@sname@"
+_0_@sname@ = omniORB.openModule("@package@@sname@", r"@filename@")
+_0_@s_sname@ = omniORB.openModule("@package@@s_sname@", r"@filename@")
+"""
+
+module_end = """
+#
+# End of module "@sname@"
+#
+__name__ = "@package@@modname@"
+"""
+
+import_idl_file = """\
+# #include "@idlfile@"
+import @ifilename@"""
+
+open_imported_module_name = """\
+_0_@imodname@ = omniORB.openModule("@package@@imodname@")
+_0_@s_imodname@ = omniORB.openModule("@package@@s_imodname@")"""
+
+forward_interface = """\
+
+# @abstract@interface @ifid@;
+_0_@modname@._d_@ifid@ = (omniORB.tcInternal.@tvkind@, "@repoId@", "@ifid@")
+omniORB.typeMapping["@repoId@"] = _0_@modname@._d_@ifid@"""
+
+
+interface_class = """\
+
+# @abstract@interface @ifid@
+_0_@modname@._d_@ifid@ = (omniORB.tcInternal.@tvkind@, "@repoId@", "@ifid@")
+omniORB.typeMapping["@repoId@"] = _0_@modname@._d_@ifid@
+_0_@modname@.@ifid@ = omniORB.newEmptyClass()
+class @ifid@ @inherits@:
+    _NP_RepositoryId = _0_@modname@._d_@ifid@[1]
+
+    def __init__(self, *args, **kw):
+        raise RuntimeError("Cannot construct objects of this type.")
+
+    _nil = CORBA.Object._nil
+"""
+
+interface_descriptor = """
+_0_@modname@.@ifid@ = @ifid@
+_0_@modname@._tc_@ifid@ = omniORB.tcInternal.createTypeCode(_0_@modname@._d_@ifid@)
+omniORB.registerType(@ifid@._NP_RepositoryId, _0_@modname@._d_@ifid@, _0_@modname@._tc_@ifid@)"""
+
+callables_header = """
+# @ifid@ operations and attributes"""
+
+attribute_get_descriptor = """\
+@ifid@._d__get_@attr@ = ((),(@descr@,),None)"""
+
+attribute_set_descriptor = """\
+@ifid@._d__set_@attr@ = ((@descr@,),(),None)"""
+
+operation_descriptor = """\
+@ifid@._d_@opname@ = (@inds@, @outds@, @excs@@options@)"""
+
+objref_class = """\
+
+# @ifid@ object reference
+class _objref_@ifid@ (@inherits@):
+    _NP_RepositoryId = @ifid@._NP_RepositoryId
+
+    def __init__(self):"""
+
+objref_inherit_init = """\
+        @inclass@.__init__(self)"""
+
+objref_object_init = """\
+        CORBA.Object.__init__(self)"""
+
+objref_attribute_get = """
+    def _get_@attr@(self, *args):
+        return _omnipy.invoke(self, "_get_@attr@", _0_@modname@.@ifid@._d__get_@attr@, args)"""
+objref_attribute_set = """
+    def _set_@attr@(self, *args):
+        return _omnipy.invoke(self, "_set_@attr@", _0_@modname@.@ifid@._d__set_@attr@, args)"""
+objref_operation = """
+    def @opname@(self, *args):
+        return _omnipy.invoke(self, "@r_opname@", _0_@modname@.@ifid@._d_@opname@, args)"""
+objref_methods = """
+    __methods__ = @methods@"""
+
+objref_register = """
+omniORB.registerObjref(@ifid@._NP_RepositoryId, _objref_@ifid@)
+_0_@modname@._objref_@ifid@ = _objref_@ifid@
+del @ifid@, _objref_@ifid@"""
+
+skeleton_class = """
+# @ifid@ skeleton
+__name__ = "@package@@s_modname@"
+class @ifid@ (@inherits@):
+    _NP_RepositoryId = _0_@modname@.@ifid@._NP_RepositoryId
+"""
+
+skeleton_methodmap = """
+    _omni_op_d = @methodmap@"""
+
+skeleton_inheritmap = """\
+    _omni_op_d.update(@inheritclass@._omni_op_d)"""
+
+skeleton_end = """
+@ifid@._omni_skeleton = @ifid@
+_0_@s_modname@.@ifid@ = @ifid@
+omniORB.registerSkeleton(@ifid@._NP_RepositoryId, @ifid@)
+del @ifid@
+__name__ = "@package@@modname@"\
+"""
+
+skeleton_set_skel = """
+@ifid@._omni_skeleton = @ifid@
+"""
+
+constant_at_module_scope = """\
+_0_@modname@.@cname@ = @value@"""
+
+constant = """\
+@cname@ = @value@"""
+
+typedef_header = """\
+
+# typedef ... @tdname@
+class @tdname@:
+    _NP_RepositoryId = "@repoId@"
+    def __init__(self, *args, **kw):
+        raise RuntimeError("Cannot construct objects of this type.")"""
+
+typedef_struct_union_header = """\
+
+# typedef ... @tdname@
+class @tdname@ (@parent@):
+    _NP_RepositoryId = "@repoId@"
+"""
+
+typedef_fixed_header = """\
+# typedef ... @tdname@
+@tdname@ = omniORB.fixedConstructor("@repoId@", @digits@, @scale@)"""
+
+typedef_at_module_scope = """\
+_0_@modname@.@tdname@ = @tdname@
+_0_@modname@._d_@tdname@  = @desc@
+_0_@modname@._ad_@tdname@ = (omniORB.tcInternal.tv_alias, @tdname@._NP_RepositoryId, "@tdname@", @tddesc@)
+_0_@modname@._tc_@tdname@ = omniORB.tcInternal.createTypeCode(_0_@modname@._ad_@tdname@)
+omniORB.registerType(@tdname@._NP_RepositoryId, _0_@modname@._ad_@tdname@, _0_@modname@._tc_@tdname@)
+del @tdname@"""
+
+typedef = """\
+_d_@tdname@  = @desc@
+_ad_@tdname@ = (omniORB.tcInternal.tv_alias, @tdname@._NP_RepositoryId, "@tdname@", @tddesc@)
+_tc_@tdname@ = omniORB.tcInternal.createTypeCode(_ad_@tdname@)
+omniORB.registerType(@tdname@._NP_RepositoryId, _ad_@tdname@, _tc_@tdname@)"""
+
+forward_struct_descr_at_module_scope = """
+# Forward struct @sname@
+_0_@modname@._d_@sname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
+omniORB.typeMapping["@repoId@"] = _0_@modname@._d_@sname@"""
+
+forward_struct_descr = """
+# Forward struct @sname@
+_d_@sname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
+omniORB.typeMapping["@repoId@"] = _d_@sname@"""
+
+recursive_struct_descr_at_module_scope = """
+# Recursive struct @sname@
+_0_@modname@._d_@sname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
+omniORB.typeMapping["@repoId@"] = _0_@modname@._d_@sname@"""
+
+recursive_struct_descr = """
+# Recursive struct @sname@
+_d_@sname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
+_0_@scope@._d_@sname@ = _d_@sname@
+omniORB.typeMapping["@repoId@"] = _d_@sname@"""
+
+struct_class = """
+# struct @sname@
+_0_@scopedname@ = omniORB.newEmptyClass()
+class @sname@ (omniORB.StructBase):
+    _NP_RepositoryId = "@repoId@"
+"""
+
+struct_class_name = """\
+    _NP_ClassName = "@cname@"
+"""
+
+struct_class_init = """\
+    def __init__(self@mnames@):"""
+
+struct_init_member = """\
+        self.@mname@ = @mname@"""
+
+struct_descriptor_at_module_scope = """\
+
+_0_@modname@.@sname@ = @sname@
+_0_@modname@._d_@sname@  = (omniORB.tcInternal.tv_struct, @sname@, @sname@._NP_RepositoryId, "@sname@"@mdescs@)"""
+
+struct_register_at_module_scope = """\
+_0_@modname@._tc_@sname@ = omniORB.tcInternal.createTypeCode(_0_@modname@._d_@sname@)
+omniORB.registerType(@sname@._NP_RepositoryId, _0_@modname@._d_@sname@, _0_@modname@._tc_@sname@)
+del @sname@"""
+
+struct_descriptor = """\
+
+_d_@sname@  = _0_@scope@._d_@sname@ = (omniORB.tcInternal.tv_struct, @sname@, @sname@._NP_RepositoryId, "@sname@"@mdescs@)"""
+
+struct_register = """\
+_tc_@sname@ = omniORB.tcInternal.createTypeCode(_d_@sname@)
+omniORB.registerType(@sname@._NP_RepositoryId, _d_@sname@, _tc_@sname@)"""
+
+struct_module_descriptors = """
+_0_@modname@._d_@sname@  = _d_@sname@
+_0_@modname@._tc_@sname@ = _tc_@sname@
+del @sname@, _d_@sname@, _tc_@sname@"""
+
+exception_class = """\
+
+# exception @sname@
+_0_@scopedname@ = omniORB.newEmptyClass()
+class @sname@ (CORBA.UserException):
+    _NP_RepositoryId = "@repoId@"
+"""
+
+exception_class_init = """\
+    def __init__(self@mnames@):
+        CORBA.UserException.__init__(self@mnames@)"""
+
+exception_init_member = """\
+        self.@mname@ = @mname@"""
+
+exception_descriptor_at_module_scope = """\
+
+_0_@modname@.@sname@ = @sname@
+_0_@modname@._d_@sname@  = (omniORB.tcInternal.tv_except, @sname@, @sname@._NP_RepositoryId, "@sname@"@mdescs@)
+_0_@modname@._tc_@sname@ = omniORB.tcInternal.createTypeCode(_0_@modname@._d_@sname@)
+omniORB.registerType(@sname@._NP_RepositoryId, _0_@modname@._d_@sname@, _0_@modname@._tc_@sname@)
+del @sname@"""
+
+exception_descriptor = """\
+
+_d_@sname@  = (omniORB.tcInternal.tv_except, @sname@, @sname@._NP_RepositoryId, "@sname@"@mdescs@)
+_tc_@sname@ = omniORB.tcInternal.createTypeCode(_d_@sname@)
+omniORB.registerType(@sname@._NP_RepositoryId, _d_@sname@, _tc_@sname@)"""
+
+forward_union_descr_at_module_scope = """
+# Forward union @uname@
+_0_@modname@._d_@uname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
+omniORB.typeMapping["@repoId@"] = _0_@modname@._d_@uname@"""
+
+forward_union_descr = """
+# Forward union @uname@
+_d_@uname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
+omniORB.typeMapping["@repoId@"] = _d_@uname@"""
+
+recursive_union_descr_at_module_scope = """
+# Recursive union @uname@
+_0_@modname@._d_@uname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
+omniORB.typeMapping["@repoId@"] = _0_@modname@._d_@uname@"""
+
+recursive_union_descr = """
+# Recursive union @uname@
+_d_@uname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
+_0_@scope@._d_@uname@ = _d_@uname@
+omniORB.typeMapping["@repoId@"] = _d_@uname@"""
+
+union_class = """
+# union @uname@
+_0_@scopedname@ = omniORB.newEmptyClass()
+class @uname@ (omniORB.Union):
+    _NP_RepositoryId = "@repoId@"\
+"""
+
+union_class_name = """\
+    _NP_ClassName = "@cname@"
+"""
+
+union_descriptor_at_module_scope = """
+_0_@modname@.@uname@ = @uname@
+
+@uname@._m_to_d = {@m_to_d@}
+@uname@._d_to_m = {@d_to_m@}
+@uname@._def_m  = @def_m@
+@uname@._def_d  = @def_d@
+
+_0_@modname@._m_@uname@  = (@m_un@,)
+_0_@modname@._d_@uname@  = (omniORB.tcInternal.tv_union, @uname@, @uname@._NP_RepositoryId, "@uname@", @stype@, @defpos@, _0_@modname@._m_@uname@, @m_def@, {@d_map@})"""
+
+union_register_at_module_scope = """\
+_0_@modname@._tc_@uname@ = omniORB.tcInternal.createTypeCode(_0_@modname@._d_@uname@)
+omniORB.registerType(@uname@._NP_RepositoryId, _0_@modname@._d_@uname@, _0_@modname@._tc_@uname@)
+del @uname@"""
+
+union_descriptor = """
+@uname@._m_to_d = {@m_to_d@}
+@uname@._d_to_m = {@d_to_m@}
+@uname@._def_m  = @def_m@
+@uname@._def_d  = @def_d@
+
+_m_@uname@  = (@m_un@,)
+_d_@uname@  = _0_@scope@._d_@uname@ = (omniORB.tcInternal.tv_union, @uname@, @uname@._NP_RepositoryId, "@uname@", @stype@, @defpos@, _m_@uname@, @m_def@, {@d_map@})"""
+
+union_register = """\
+_tc_@uname@ = omniORB.tcInternal.createTypeCode(_d_@uname@)
+omniORB.registerType(@uname@._NP_RepositoryId, _d_@uname@, _tc_@uname@)"""
+
+
+enum_start = """
+# enum @ename@\
+"""
+
+enum_item_at_module_scope = """\
+_0_@modname@.@eitem@ = omniORB.EnumItem("@item@", @eval@)"""
+
+enum_object_and_descriptor_at_module_scope = """\
+_0_@modname@.@ename@ = omniORB.Enum("@repoId@", (@eitems@,))
+
+_0_@modname@._d_@ename@  = (omniORB.tcInternal.tv_enum, _0_@modname@.@ename@._NP_RepositoryId, "@ename@", _0_@modname@.@ename@._items)
+_0_@modname@._tc_@ename@ = omniORB.tcInternal.createTypeCode(_0_@modname@._d_@ename@)
+omniORB.registerType(_0_@modname@.@ename@._NP_RepositoryId, _0_@modname@._d_@ename@, _0_@modname@._tc_@ename@)"""
+
+enum_item = """\
+@eitem@ = omniORB.EnumItem("@item@", @eval@)"""
+
+enum_object_and_descriptor = """\
+@ename@ = omniORB.Enum("@repoId@", (@eitems@,))
+
+_d_@ename@  = (omniORB.tcInternal.tv_enum, @ename@._NP_RepositoryId, "@ename@", @ename@._items)
+_tc_@ename@ = omniORB.tcInternal.createTypeCode(_d_@ename@)
+omniORB.registerType(@ename@._NP_RepositoryId, _d_@ename@, _tc_@ename@)"""
+
+
+value_forward_at_module_scope = """\
+# forward valuetype @vname@
+_0_@modname@._d_@vname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
+omniORB.typeMapping["@repoId@"] = _0_@modname@._d_@vname@
+"""
+
+value_class = """
+# valuetype @vname@
+_0_@modname@._d_@vname@ = (omniORB.tcInternal.tv__indirect, ["@repoId@"])
+omniORB.typeMapping["@repoId@"] = _0_@modname@._d_@vname@
+_0_@modname@.@vname@ = omniORB.newEmptyClass()
+
+class @vname@ (@inherits@):
+    _NP_RepositoryId = "@repoId@"
+
+    def __init__(self, *args, **kwargs):
+        if args:
+            if len(args) != @arglen@:
+                raise TypeError("@vname@() takes @arglen@ argument@s@ "
+                                "(%d given)" % len(args))
+            @set_args@
+        if kwargs:
+            self.__dict__.update(kwargs)
+"""
+
+valueabs_class = """\
+class @vname@ (@inherits@):
+    _NP_RepositoryId = "@repoId@"
+
+    def __init__(self, *args, **kwargs):
+        raise RuntimeError("Cannot construct objects of this type.")
+"""
+
+value_register_factory = """\
+omniORB.registerValueFactory(@vname@._NP_RepositoryId, @vname@)
+"""
+
+value_descriptor_at_module_scope = """\
+_0_@modname@.@vname@ = @vname@
+_0_@modname@._d_@vname@  = (omniORB.tcInternal.tv_value, @vname@, @vname@._NP_RepositoryId, "@vname@", @modifier@, @tbaseids@, @basedesc@, @mdescs@)
+_0_@modname@._tc_@vname@ = omniORB.tcInternal.createTypeCode(_0_@modname@._d_@vname@)
+omniORB.registerType(@vname@._NP_RepositoryId, _0_@modname@._d_@vname@, _0_@modname@._tc_@vname@)
+del @vname@
+"""
+
+value_objref_register = """
+omniORB.registerObjref(@ifid@._NP_RepositoryId, _objref_@ifid@)
+_0_@modname@._objref_@ifid@ = _objref_@ifid@
+del _objref_@ifid@"""
+
+
+valuebox = """\
+
+# valuebox @boxname@
+class @boxname@:
+    _NP_RepositoryId = "@repoId@"
+    def __init__(self, *args, **kw):
+        raise RuntimeError("Cannot construct objects of this type.")
+
+_0_@modname@.@boxname@ = @boxname@
+_0_@modname@._d_@boxname@  = (omniORB.tcInternal.tv_value_box, @boxname@, @boxname@._NP_RepositoryId, "@boxname@", @boxdesc@)
+_0_@modname@._tc_@boxname@ = omniORB.tcInternal.createTypeCode(_0_@modname@._d_@boxname@)
+omniORB.registerType(@boxname@._NP_RepositoryId, _0_@modname@._d_@boxname@, _0_@modname@._tc_@boxname@)
+omniORB.registerValueFactory(@boxname@._NP_RepositoryId, @boxname@)
+del @boxname@
+"""
+
+
+example_start = """\
+#!/usr/bin/env python
+
+# Python example implementations generated from @filename@
+
+import CORBA, PortableServer
+
+# Import the Python stub modules so type definitions are available.
+"""
+
+example_import_skels = """
+# Import the Python Skeleton modules so skeleton base classes are available.
+"""
+
+example_import = """\
+import @module@"""
+
+example_classdef = """
+
+# Implementation of interface @ccname@
+
+class @ifname@_i (@skname@):
+@inheritance_note@
+    def __init__(self):
+        # Initialise member variables here
+        pass
+"""
+
+example_opdef = """\
+    # @signature@
+    def @opname@(self@args@):
+        raise CORBA.NO_IMPLEMENT(0, CORBA.COMPLETED_NO)
+        # *** Implement me
+        # Must return: @returnspec@
+"""
+
+example_end = """
+if __name__ == "__main__":
+    import sys
+    
+    # Initialise the ORB
+    orb = CORBA.ORB_init(sys.argv)
+    
+    # As an example, we activate an object in the Root POA
+    poa = orb.resolve_initial_references("RootPOA")
+
+    # Create an instance of a servant class
+    servant = @ifname@_i()
+
+    # Activate it in the Root POA
+    poa.activate_object(servant)
+
+    # Get the object reference to the object
+    objref = servant._this()
+    
+    # Print a stringified IOR for it
+    print orb.object_to_string(objref)
+
+    # Activate the Root POA's manager
+    poa._get_the_POAManager().activate()
+
+    # Run the ORB, blocking this thread
+    orb.run()
+"""
+
+
+# Global state
+imported_files   = {}
+exported_modules = {}
+
+# Command line options
+output_inline    = 0
+global_module    = "_GlobalIDL"
+module_package   = ""
+stub_package     = ""
+stub_directory   = ""
+all_factories    = 0
+example_impl     = 0
+extern_stub_pkgs = {}
+
+def methgrp_index(metharr,opname):
+    for i in range(0, len(metharr)):
+        if len(opname) > 2 and metharr[i] == opname[:-2]:
+            return i
+
+    return -1
+
+def ret_arg(p):
+    return "args["+str(p)+"]"
+
+def is_int(p):
+    return "(type("+ret_arg(p)+") in [IntType, LongType])"
+
+def is_boolean(p):
+    return "(type("+ret_arg(p)+") in [IntType, LongType, BooleanType])"
+
+def is_double(p):
+    return "(type("+ret_arg(p)+") in [IntType, LongType, FloatType])"
+
+def is_string(p):
+    return "(type("+ret_arg(p)+") in [StringType])"
+
+def is_vtkPtr(p):
+    return "(type("+ret_arg(p)+") in [InstanceType])"
+
+def is_list(p):
+    return "(type("+ret_arg(p)+").count('[]') > 0)"
+
+def is_any(p):
+    return "(type("+ret_arg(p)+") in [CORBA.Any])"
+
+def is_char(p):
+    return "((type("+ret_arg(p)+") in [StringType]) and (len(" + ret_arg(p) + ") == 1))"
+
+def error_exit(message):
+    sys.stderr.write(main.cmdname + ": " + message + "\n")
+    sys.exit(1)
+
+def run(tree, args):
+    global main_idl_file, imported_files, exported_modules, output_inline
+    global global_module, module_package, stub_package, stub_directory
+    global all_factories, example_impl, extern_stub_pkgs
+
+    imported_files.clear()
+    exported_modules.clear()
+
+    # Look at the args:
+    use_stdout     = 0
+    create_package = 1
+    for arg in args:
+
+        if arg == "stdout":
+            use_stdout     = 1
+            create_package = 0
+
+        elif arg == "no_package":
+            create_package = 0
+
+        elif arg == "inline":
+            output_inline = 1
+
+        elif arg == "factories":
+            all_factories = 1
+
+        elif arg[:8] == "modules=":
+            module_package = arg[8:]
+            if module_package != "":
+                module_package = module_package + "."
+
+        elif arg[:6] == "stubs=":
+            stub_package   = arg[6:]
+            stub_directory = apply(os.path.join,
+                                   string.split(stub_package, "."))
+            if stub_package != "":
+                stub_package = stub_package + "."
+
+        elif arg[:8] == "package=":
+            module_package = stub_package = arg[8:]
+            stub_directory = apply(os.path.join,
+                                   string.split(stub_package, "."))
+            if module_package != "":
+                module_package = stub_package = module_package + "."
+
+        elif arg[:7] == "global=":
+            global_module = arg[7:]
+            if global_module == "":
+                error_exit("You may not have an unnamed global module.")
+
+        elif arg == "example":
+            example_impl = 1
+
+        elif arg[:7] == "extern=":
+            f_p = string.split(arg[7:], ":", 1)
+            if len(f_p) == 1:
+                extern_stub_pkgs[f_p[0]] = None
+            else:
+                extern_stub_pkgs[f_p[0]] = f_p[1]
+
+        else:
+            sys.stderr.write(main.cmdname + ": Warning: Python " \
+                             "back-end does not understand argument: " + \
+                             arg + "\n")
+
+    main_idl_file = tree.file()
+
+    outpybasename = outputFileName(main_idl_file)
+    outpymodule   = stub_package + outpybasename
+    outpyname     = os.path.join(stub_directory, outpybasename + ".py")
+
+    imported_files[outpybasename] = 1
+
+    if create_package:
+        checkStubPackage(stub_package)
+
+    if use_stdout:
+        st = output.Stream(sys.stdout, 4)
+    else:
+        try:
+            st = output.Stream(open(outpyname, "w"), 4)
+        except IOError:
+            error_exit('Cannot open "%s" for writing.' % outpyname)
+
+    st.out(file_start, filename=main_idl_file)
+
+    pv = PythonVisitor(st, outpymodule)
+    tree.accept(pv)
+
+    dv = DocstringVisitor(st)
+    tree.accept(dv)
+    dv.output()
+
+    exports = exported_modules.keys()
+    exports.sort()
+    export_list = map(lambda s: '"' + module_package + s + '"', exports)
+    if len(export_list) == 1: export_list.append("")
+    export_string = string.join(export_list, ", ")
+
+    st.out(file_end, export_string=export_string)
+
+    if create_package:
+        updateModules(exports, outpymodule)
+
+    if example_impl:
+        implname = os.path.join(stub_directory, outpybasename + "_example.py")
+        exst = output.Stream(open(implname, "w"), 4)
+        exst.out(example_start, filename=main_idl_file)
+        for mod in exports:
+            exst.out(example_import, module=mod)
+        exst.out(example_import_skels)
+        for mod in exports:
+            exst.out(example_import, module=skeletonModuleName(mod))
+
+        ev = ExampleVisitor(exst)
+        tree.accept(ev)
+
+        exst.out(example_end, ifname=ev.first)
+
+
+class PythonVisitor:
+    def __init__(self, st, outpymodule):
+        self.st          = st
+        self.outpymodule = outpymodule
+
+    def handleImported(self, node):
+        global imported_files
+
+        if node.mainFile() or output_inline:
+            return 0
+        else:
+            ifilename = outputFileName(node.file())
+            if not imported_files.has_key(ifilename):
+                imported_files[ifilename] = 1
+                ibasename,ext = os.path.splitext(os.path.basename(node.file()))
+                if extern_stub_pkgs.has_key(ibasename):
+                    ipackage = extern_stub_pkgs[ibasename]
+                    if ipackage:
+                        fn = ipackage + '.' + ifilename
+                    else:
+                        fn = ifilename
+                else:
+                    fn = stub_package + ifilename
+
+                self.st.out(import_idl_file,
+                            idlfile=node.file(),
+                            ifilename=fn)
+            return 1
+        
+    #
+    # The global module
+    #
+    def visitAST(self, node):
+        self.at_module_scope = 1
+        self.at_global_scope = 1
+        self.currentScope    = ["_0_" + global_module]
+
+        decls_in_global_module = 0
+
+        for n in node.declarations():
+            if not isinstance(n, idlast.Module):
+                decls_in_global_module = 1
+                break
+
+        if decls_in_global_module:
+            self.modname = global_module
+            self.st.out(module_start,
+                        sname=global_module,
+                        s_sname=skeletonModuleName(global_module),
+                        filename=node.file(), package=module_package)
+        else:
+            self.modname = self.outpymodule
+
+        for n in node.declarations():
+            n.accept(self)
+
+        if decls_in_global_module:
+            exported_modules[global_module] = 1
+            self.st.out(module_end, modname=self.outpymodule,
+                        sname=global_module,
+                        package="")
+
+    #
+    # Module
+    #
+    def visitModule(self, node):
+        if self.handleImported(node):
+            imodname = dotName(node.scopedName())
+            ibasename,ext = os.path.splitext(os.path.basename(node.file()))
+
+            if extern_stub_pkgs.has_key(ibasename):
+                package = extern_stub_pkgs[ibasename]
+                if package is None:
+                    package = ""
+                else:
+                    package = package + "."
+            else:
+                package = module_package
+
+            self.st.out(open_imported_module_name,
+                        imodname=imodname,
+                        s_imodname=skeletonModuleName(imodname),
+                        package=package)
+
+        assert self.at_module_scope
+
+        sname = dotName(node.scopedName())
+
+        if node.mainFile() or output_inline:
+            self.st.out(module_start,
+                        sname = sname,
+                        s_sname = skeletonModuleName(sname),
+                        filename = node.file(), package=module_package)
+
+        parentmodname = self.modname
+        self.modname  = dotName(node.scopedName())
+
+        ags = self.at_global_scope
+        if ags:
+            self.currentScope = ["_0_" + node.identifier()]
+        else:
+            self.currentScope.append(node.identifier())
+
+        self.at_global_scope = 0
+
+        for n in node.definitions():
+            n.accept(self)
+
+        if ags:
+            self.currentScope = ["_0_" + global_module]
+        else:
+            self.currentScope.pop()
+        self.at_global_scope = ags
+        self.modname         = parentmodname
+
+        if node.mainFile() or output_inline:
+            exported_modules[sname] = 1
+            self.st.out(module_end, modname=parentmodname, sname=sname,
+                        package=module_package)
+
+    #
+    # Forward interface
+    #
+    def visitForward(self, node):
+        if self.handleImported(node): return
+
+        assert self.at_module_scope
+        ifid   = mangle(node.identifier())
+        repoId = node.repoId()
+        if node.abstract():
+            tvkind = "tv_abstract_interface"
+            abstract = "abstract "
+        else:
+            tvkind = "tv_objref"
+            abstract = ""
+
+        self.st.out(forward_interface, ifid=ifid, tvkind=tvkind,
+                    repoId=repoId, abstract=abstract, modname=self.modname)
+
+    #
+    # Interface
+    #
+    def visitInterface(self, node):
+        if self.handleImported(node): return
+
+        assert self.at_module_scope
+        ifid = mangle(node.identifier())
+
+        if len(node.inherits()) > 0:
+            inheritl = []
+            for i in node.inherits():
+                i = i.fullDecl()
+                inheritl.append(dotName(fixupScopedName(i.scopedName())))
+            
+            inherits = "(" + string.join(inheritl, ", ") + ")"
+        else:
+            inherits = ""
+
+        if node.abstract():
+            tvkind = "tv_abstract_interface"
+            abstract = "abstract "
+        else:
+            tvkind = "tv_objref"
+            abstract = ""
+
+        # Class header
+        self.st.out(interface_class, ifid=ifid, tvkind=tvkind,
+                    inherits=inherits, repoId=node.repoId(),
+                    abstract=abstract, modname=self.modname)
+
+        # Declarations within the interface
+        if len(node.declarations()) > 0:
+            self.st.inc_indent()
+            self.at_module_scope = 0
+            self.currentScope.append(node.identifier())
+
+            for d in node.declarations():
+                d.accept(self)
+
+            self.currentScope.pop()
+            self.at_module_scope = 1
+            self.st.dec_indent()
+            self.st.out("")
+
+        # Descriptor and TypeCode for the interface
+        self.st.out(interface_descriptor,
+                    modname = self.modname, ifid = ifid)
+
+        # Attributes and operations
+        # *** Was there a good reason for putting these in the class def?
+        if len(node.callables()) > 0:
+            self.st.out(callables_header, ifid=ifid)
+
+        for c in node.callables():
+            if isinstance(c, idlast.Attribute):
+
+                descr = typeToDescriptor(c.attrType())
+
+                for attr in c.identifiers():
+
+                    self.st.out(attribute_get_descriptor,
+                                attr=attr, descr=descr, ifid=ifid)
+
+                    if not c.readonly():
+
+                        self.st.out(attribute_set_descriptor,
+                                    attr=attr, descr=descr, ifid=ifid)
+            else: # Operation
+
+                inds, outds, excs, ctxts, cv = operationToDescriptors(c)
+
+                options = ""
+
+                if cv:
+                    ctxts = ctxts or "None"
+
+                if ctxts:
+                    options = ", " + ctxts
+
+                if cv:
+                    options = options + ", 1"
+
+                # Output the declaration
+                self.st.out(operation_descriptor,
+                            opname  = mangle(c.identifier()),
+                            inds    = inds,
+                            outds   = outds,
+                            excs    = excs,
+                            options = options,
+                            ifid    = ifid)
+
+        # Objref class
+        if node.inherits():
+            inheritl = []
+            for i in node.inherits():
+                i = i.fullDecl()
+                sn = fixupScopedName(i.scopedName())
+                inheritl.append(dotName(sn[:-1] + ["_objref_" + sn[-1]]))
+                
+            inherits = string.join(inheritl, ", ")
+        else:
+            inherits = "CORBA.Object"
+
+        self.st.out(objref_class, ifid=ifid, inherits=inherits)
+
+        if node.inherits():
+            for inclass in inheritl:
+                self.st.out(objref_inherit_init, inclass=inclass)
+        else:
+            self.st.out(objref_object_init)
+
+        # Operations and attributes
+        methodl = []
+        methadd = []
+        methdsc = []
+
+        for c in node.callables():
+
+            if isinstance(c, idlast.Attribute):
+
+                for attr in c.identifiers():
+
+                    self.st.out(objref_attribute_get,
+                                attr    = attr,
+                                ifid    = ifid,
+                                modname = self.modname)
+                    
+                    methodl.append('"_get_' + attr + '"')
+
+                    if not c.readonly():
+
+                        self.st.out(objref_attribute_set,
+                                    attr    = attr,
+                                    ifid    = ifid,
+                                    modname = self.modname)
+                        
+                        methodl.append('"_set_' + attr + '"')
+
+            else: # Operation
+                opname = mangle(c.identifier())
+                
+                if len(opname) > 2 and opname[-2] == '_':
+                    methlen = methgrp_index(methadd,opname)
+                    if methlen < 0:
+                        methodl.append('"' + opname[:-2] + '"')
+
+                        methlen = len(methadd)
+
+                        methadd = methadd + [opname[:-2]]
+
+                        methdsc = methdsc + [""]
+                        methdsc[methlen] = "\n    def "+opname[:-2]+"(self, *args):"
+
+                    methdsc[methlen] = methdsc[methlen] + "\n        "
+                        
+                    methdsc[methlen] = methdsc[methlen] + "if len(args) == " + str(len(c.parameters()))
+
+                    for p in range(0,len(c.parameters())):
+                        methdsc[methlen] = methdsc[methlen] + " and "
+                        if c.parameters()[p].paramType().kind() in [idltype.tk_short,idltype.tk_long]:
+                            methdsc[methlen] = methdsc[methlen] + is_int(p)
+                        if c.parameters()[p].paramType().kind() in [idltype.tk_float,idltype.tk_double]:
+                            methdsc[methlen] = methdsc[methlen] + is_double(p)
+                        if c.parameters()[p].paramType().kind() in [idltype.tk_string]:
+                            methdsc[methlen] = methdsc[methlen] + is_string(p)
+                        if c.parameters()[p].paramType().kind() in [idltype.tk_sequence,idltype.tk_alias]:
+                            methdsc[methlen] = methdsc[methlen] + is_list(p)
+                        if c.parameters()[p].paramType().kind() in [idltype.tk_objref]:
+                            methdsc[methlen] = methdsc[methlen] + is_vtkPtr(p)
+                        if c.parameters()[p].paramType().kind() in [idltype.tk_boolean]:
+                            methdsc[methlen] = methdsc[methlen] + is_boolean(p)
+                        if c.parameters()[p].paramType().kind() in [idltype.tk_any]:
+                            methdsc[methlen] = methdsc[methlen] + is_any(p)
+                        if c.parameters()[p].paramType().kind() in [idltype.tk_char]:
+                            methdsc[methlen] = methdsc[methlen] + is_char(p)
+                        if c.parameters()[p].paramType().kind() not in [idltype.tk_boolean,idltype.tk_short,idltype.tk_long,idltype.tk_float,idltype.tk_double,idltype.tk_string,idltype.tk_sequence,idltype.tk_alias,idltype.tk_objref,idltype.tk_any,idltype.tk_char]:
+                            methdsc[methlen] = methdsc[methlen] + " " + str(c.parameters()[p].paramType().kind()) + " == '' "
+
+                    methdsc[methlen] = methdsc[methlen] + ":"
+                    methdsc[methlen] = methdsc[methlen] + "\n            return self."+opname+"(*args)"
+
+                self.st.out(objref_operation,
+                            opname   = opname,
+                            r_opname = c.identifier(),
+                            ifid     = ifid,
+                            modname  = self.modname)
+                methodl.append('"' + opname + '"')
+
+        for p in range(0,len(methadd)):
+            methgrp = methadd[p]
+            methtmp = methdsc[p]
+            methtmp = methtmp + "\n        print 'Warning: The corresponding method of " + methgrp + " group is not found for ' + str(args)"
+            self.st.out(methtmp)
+
+        #self.st.out("\n    def __eq__(self,other):")
+        #self.st.out("        return self.IsSame(other)==0")
+
+        # __methods__ assignment
+        methods = "[" + string.join(methodl, ", ") + "]"
+
+        if node.inherits():
+            inheritl = []
+            for i in node.inherits():
+                i = i.fullDecl()
+                sn = fixupScopedName(i.scopedName())
+                methods = methods + " + " + \
+                          dotName(sn[:-1] + ["_objref_" + sn[-1]]) + \
+                          ".__methods__"
+        else:
+            methods = methods + " + CORBA.Object.__methods__"
+
+        self.st.out(objref_methods, methods = methods)
+
+        # registerObjRef()
+        self.st.out(objref_register, ifid = ifid, modname = self.modname)
+
+        # Skeleton class
+        if node.inherits():
+            inheritl = []
+            for i in node.inherits():
+                i = i.fullDecl()
+                fsn = fixupScopedName(i.scopedName())
+                dsn = dotName(fsn)
+                ssn = skeletonModuleName(dsn)
+                inheritl.append(ssn)
+                
+            inherits = string.join(inheritl, ", ")
+        else:
+            inherits = "PortableServer.Servant"
+
+        self.st.out(skeleton_class,
+                    ifid      = ifid,
+                    inherits  = inherits,
+                    modname   = self.modname,
+                    s_modname = skeletonModuleName(self.modname),
+                    package   = module_package)
+
+        # Operations and attributes
+        methodl = []
+
+        for c in node.callables():
+            if isinstance(c, idlast.Attribute):
+
+                for attr in c.identifiers():
+
+                    methodl.append('"_get_' + attr + '": ' + \
+                                   '_0_' + self.modname + '.' + \
+                                   ifid + '.' + '_d__get_' + attr)
+
+                    if not c.readonly():
+
+                        methodl.append('"_set_' + attr + '": ' + \
+                                       '_0_' + self.modname + '.' + \
+                                       ifid + '.' + '_d__set_' + attr)
+
+            else: # Operation
+                opname = mangle(c.identifier())
+                
+                methodl.append('"' + opname + '": ' + '_0_' + self.modname + \
+                               '.' + ifid + '.' + '_d_' + opname)
+
+        methodmap = "{" + string.join(methodl, ", ") + "}"
+
+        self.st.out(skeleton_methodmap, methodmap = methodmap)
+
+        if node.inherits():
+            for inheritclass in inheritl:
+                self.st.out(skeleton_inheritmap, inheritclass = inheritclass)
+
+        self.st.out(skeleton_end,
+                    ifid      = ifid,
+                    modname   = self.modname,
+                    s_modname = skeletonModuleName(self.modname),
+                    package   = module_package)
+
+    #
+    # Constant
+    #
+    def visitConst(self, node):
+        if self.handleImported(node): return
+
+        cname = mangle(node.identifier())
+
+        if self.at_module_scope:
+            value = valueToString(node.value(), node.constKind(), [])
+        else:
+            value = valueToString(node.value(), node.constKind(),
+                                  self.currentScope)
+        if self.at_module_scope:
+            self.st.out(constant_at_module_scope,
+                        cname   = cname,
+                        value   = value,
+                        modname = self.modname)
+        else:
+            self.st.out(constant,
+                        cname   = cname,
+                        value   = value)
+
+    #
+    # Typedef
+    #
+    def visitTypedef(self, node):
+        if self.handleImported(node): return
+
+        if node.constrType():
+            node.aliasType().decl().accept(self)
+
+        for decl in node.declarators():
+            tdname = mangle(decl.identifier())
+            if self.at_module_scope:
+                desc   = typeAndDeclaratorToDescriptor(node.aliasType(),
+                                                       decl, [])
+                tddesc = typeAndDeclaratorToDescriptor(node.aliasType(),
+                                                       decl, [], 1)
+
+                unaliased_type = node.aliasType().unalias()
+
+                if len(decl.sizes()) == 0 and \
+                   unaliased_type.kind() in [idltype.tk_struct,
+                                             idltype.tk_union]:
+
+                    parent = dotName(fixupScopedName(unaliased_type.decl().\
+                                                     scopedName()))
+
+                    self.st.out(typedef_struct_union_header,
+                                tdname = tdname,
+                                repoId = decl.repoId(),
+                                parent = parent)
+
+                elif len(decl.sizes()) == 0 and\
+                     unaliased_type.kind() == idltype.tk_fixed:
+
+                    self.st.out(typedef_fixed_header,
+                                tdname = tdname,
+                                repoId = decl.repoId(),
+                                digits = unaliased_type.digits(),
+                                scale  = unaliased_type.scale())
+                    
+                else:
+                    self.st.out(typedef_header,
+                                tdname  = tdname,
+                                repoId  = decl.repoId())
+
+                self.st.out(typedef_at_module_scope,
+                            tdname  = tdname,
+                            desc    = desc,
+                            tddesc  = tddesc,
+                            modname = self.modname)
+            else:
+                desc   = typeAndDeclaratorToDescriptor(node.aliasType(),
+                                                       decl,
+                                                       self.currentScope)
+                tddesc = typeAndDeclaratorToDescriptor(node.aliasType(),
+                                                       decl,
+                                                       self.currentScope, 1)
+
+                unaliased_type = node.aliasType().unalias()
+
+                if len(decl.sizes()) == 0 and \
+                   unaliased_type.kind() in [idltype.tk_struct,
+                                             idltype.tk_union]:
+
+                    psname  = unaliased_type.decl().scopedName()
+                    myscope = decl.scopedName()[:-1]
+
+                    # If the struct/union definition is in the same
+                    # scope as the typedef, we must use a relative
+                    # name to refer to the parent class, since the
+                    # enclosing Python class has not yet been fully
+                    # defined.
+
+                    if psname[:len(myscope)] == myscope:
+                        parent = dotName(psname[len(myscope):])
+                    else:
+                        parent = dotName(fixupScopedName(psname))
+
+                    self.st.out(typedef_struct_union_header,
+                                tdname = tdname,
+                                repoId = decl.repoId(),
+                                parent = parent)
+                else:
+                    self.st.out(typedef_header,
+                                tdname  = tdname,
+                                repoId  = decl.repoId())
+
+                self.st.out(typedef,
+                            tdname  = tdname,
+                            desc    = desc,
+                            tddesc  = tddesc)
+    #
+    # Struct
+    #
+    def visitStruct(self, node):
+        if self.handleImported(node): return
+
+        sname = mangle(node.identifier())
+
+        fscopedName = fixupScopedName(node.scopedName(), "")
+
+        if node.recursive():
+            if self.at_module_scope:
+                self.st.out(recursive_struct_descr_at_module_scope,
+                            sname   = sname,
+                            repoId  = node.repoId(),
+                            modname = self.modname)
+            else:
+                self.st.out(recursive_struct_descr,
+                            sname   = sname,
+                            repoId  = node.repoId(),
+                            scope   = dotName(fscopedName[:-1]))
+
+        self.st.out(struct_class,
+                    sname      = sname,
+                    repoId     = node.repoId(),
+                    scopedname = dotName(fscopedName))
+
+        if not self.at_module_scope:
+            self.st.out(struct_class_name, cname = dotName(fscopedName))
+
+        mnamel = []
+        mdescl = []
+        for mem in node.members():
+
+            # Deal with nested declarations
+            if mem.constrType():
+                self.st.inc_indent()
+                ams = self.at_module_scope
+                self.at_module_scope = 0
+                self.currentScope.append(node.identifier())
+                
+                mem.memberType().decl().accept(self)
+
+                self.currentScope.pop()
+                self.at_module_scope = ams
+                self.st.dec_indent()
+                self.st.out("")
+
+            for decl in mem.declarators():
+                mnamel.append(mangle(decl.identifier()))
+                mdescl.append('"' + mangle(decl.identifier()) + '"')
+                
+                if self.at_module_scope:
+                    mdescl.append(\
+                        typeAndDeclaratorToDescriptor(mem.memberType(),
+                                                      decl,
+                                                      []))
+                else:
+                    mdescl.append(\
+                        typeAndDeclaratorToDescriptor(mem.memberType(),
+                                                      decl,
+                                                      self.currentScope))
+        if len(mnamel) > 0:
+            mnames = ", " + string.join(mnamel, ", ")
+
+            self.st.out(struct_class_init, mnames = mnames)
+
+            for mname in mnamel:
+                self.st.out(struct_init_member, mname = mname)
+
+        if len(mdescl) > 0:
+            mdescs = ", " + string.join(mdescl, ", ")
+        else:
+            mdescs = ""
+
+        if self.at_module_scope:
+            self.st.out(struct_descriptor_at_module_scope,
+                        sname   = sname,
+                        mdescs  = mdescs,
+                        modname = self.modname)
+            
+            self.st.out(struct_register_at_module_scope,
+                        sname   = sname,
+                        modname = self.modname)
+        else:
+            self.st.out(struct_descriptor,
+                        sname  = sname,
+                        mdescs = mdescs,
+                        scope  = dotName(fscopedName[:-1]))
+
+            self.st.out(struct_register, sname = sname)
+
+    #
+    # Forward struct
+    #
+    def visitStructForward(self, node):
+        if self.handleImported(node): return
+
+        sname = mangle(node.identifier())
+
+        if self.at_module_scope:
+            self.st.out(forward_struct_descr_at_module_scope,
+                        sname   = sname,
+                        repoId  = node.repoId(),
+                        modname = self.modname)
+        else:
+            self.st.out(forward_struct_descr,
+                        sname   = sname,
+                        repoId  = node.repoId(),
+                        modname = self.modname)
+
+    #
+    # Exception
+    #
+    def visitException(self, node):
+        if self.handleImported(node): return
+
+        sname = mangle(node.identifier())
+        fscopedName = fixupScopedName(node.scopedName(), "")
+        self.st.out(exception_class,
+                    sname = sname,
+                    repoId = node.repoId(),
+                    scopedname = dotName(fscopedName))
+
+        if not self.at_module_scope:
+            self.st.out(struct_class_name, cname = dotName(fscopedName))
+
+        mnamel = []
+        mdescl = []
+        for mem in node.members():
+
+            # Deal with nested declarations
+            if mem.constrType():
+                self.st.inc_indent()
+                ams = self.at_module_scope
+                self.at_module_scope = 0
+                self.currentScope.append(node.identifier())
+                
+                mem.memberType().decl().accept(self)
+
+                self.currentScope.pop()
+                self.at_module_scope = ams
+                self.st.dec_indent()
+                self.st.out("")
+
+            for decl in mem.declarators():
+                mnamel.append(mangle(decl.identifier()))
+                mdescl.append('"' + mangle(decl.identifier()) + '"')
+
+                if self.at_module_scope:
+                    mdescl.append(\
+                        typeAndDeclaratorToDescriptor(mem.memberType(),
+                                                      decl,
+                                                      []))
+                else:
+                    mdescl.append(\
+                        typeAndDeclaratorToDescriptor(mem.memberType(),
+                                                      decl,
+                                                      self.currentScope))
+
+        if len(mnamel) > 0:
+            mnames = ", " + string.join(mnamel, ", ")
+        else:
+            mnames = ""
+
+        self.st.out(exception_class_init, mnames = mnames)
+
+        for mname in mnamel:
+            self.st.out(exception_init_member, mname = mname)
+
+        if len(mdescl) > 0:
+            mdescs = ", " + string.join(mdescl, ", ")
+        else:
+            mdescs = ""
+
+        if self.at_module_scope:
+            self.st.out(exception_descriptor_at_module_scope,
+                        sname = sname, mdescs = mdescs, modname = self.modname)
+        else:
+            self.st.out(exception_descriptor, sname = sname, mdescs = mdescs)
+
+    #
+    # Union
+    #
+    def visitUnion(self, node):
+        if self.handleImported(node): return
+
+        uname = mangle(node.identifier())
+        if self.at_module_scope:
+            stype = typeToDescriptor(node.switchType(), [])
+        else:
+            stype = typeToDescriptor(node.switchType(), self.currentScope)
+
+        fscopedName = fixupScopedName(node.scopedName(), "")
+        
+        if node.recursive():
+            if self.at_module_scope:
+                self.st.out(recursive_union_descr_at_module_scope,
+                            uname   = uname,
+                            repoId  = node.repoId(),
+                            modname = self.modname)
+            else:
+                self.st.out(recursive_union_descr,
+                            uname   = uname,
+                            repoId  = node.repoId(),
+                            scope   = dotName(fscopedName[:-1]))
+
+        self.st.out(union_class,
+                    uname      = uname,
+                    repoId     = node.repoId(),
+                    scopedname = dotName(fscopedName))
+
+        if not self.at_module_scope:
+            self.st.out(union_class_name, cname = dotName(fscopedName))
+
+        if node.constrType():
+            self.st.inc_indent()
+            ams = self.at_module_scope
+            self.at_module_scope = 0
+            self.currentScope.append(node.identifier())
+            
+            node.switchType().decl().accept(self)
+
+            self.currentScope.pop()
+            self.at_module_scope = ams
+            self.st.dec_indent()
+
+        def_m    = "None"
+        def_d    = "None"
+        m_def    = "None"
+        defpos   = "-1"
+        m_to_d_l = []
+        d_to_m_l = []
+        m_un_l   = []
+        d_map_l  = []
+
+        i = 0
+        for case in node.cases():
+
+            # Deal with nested declarations
+            if case.constrType():
+                self.st.inc_indent()
+                ams = self.at_module_scope
+                self.at_module_scope = 0
+                self.currentScope.append(node.identifier())
+                
+                case.caseType().decl().accept(self)
+
+                self.currentScope.pop()
+                self.at_module_scope = ams
+                self.st.dec_indent()
+                self.st.out("")
+
+            if self.at_module_scope:
+                ctype = typeAndDeclaratorToDescriptor(case.caseType(),
+                                                      case.declarator(),
+                                                      [])
+            else:
+                ctype = typeAndDeclaratorToDescriptor(case.caseType(),
+                                                      case.declarator(),
+                                                      self.currentScope)
+
+            cname = mangle(case.declarator().identifier())
+
+            for label in case.labels():
+                if label.default():
+                    def_m  = '"' + cname + '"'
+                    defpos = str(i)
+                    if self.at_module_scope:
+                        def_d  = valueToString(label.value(),
+                                               label.labelKind(), [])
+                        m_def  = "_0_" + self.modname + "._m_" + uname + \
+                                 "[" + defpos + "]"
+                    else:
+                        def_d  = valueToString(label.value(),
+                                               label.labelKind(),
+                                               self.currentScope)
+                        m_def  = "_m_" + uname + "[" + defpos + "]"
+
+                    m_un_l.append('(' + def_d + ', "' + cname + '", ' +\
+                                  ctype + ')')
+                else:
+                    if self.at_module_scope:
+                        slabel = valueToString(label.value(),
+                                               label.labelKind(), [])
+                    else:
+                        slabel = valueToString(label.value(),
+                                               label.labelKind(),
+                                               self.currentScope)
+
+                    m_to_d_l.append('"' + cname + '": ' + slabel)
+                    d_to_m_l.append(slabel + ': "' + cname + '"')
+
+                    m_un_l.append('(' + slabel + ', "' + cname + '", ' +\
+                                  ctype + ')')
+
+                    if self.at_module_scope:
+                        d_map_l.append(slabel + ': ' + '_0_' + self.modname + \
+                                       "._m_" + uname + "[" + str(i) + "]")
+                    else:
+                        d_map_l.append(slabel + ': ' + "_m_" + \
+                                       uname + "[" + str(i) + "]")
+                i = i + 1
+
+        m_to_d = string.join(m_to_d_l, ", ")
+        d_to_m = string.join(d_to_m_l, ", ")
+        m_un   = string.join(m_un_l,   ", ")
+        d_map  = string.join(d_map_l,  ", ")
+
+        if self.at_module_scope:
+            self.st.out(union_descriptor_at_module_scope,
+                        uname   = uname,
+                        m_to_d  = m_to_d,
+                        d_to_m  = d_to_m,
+                        def_m   = def_m,
+                        def_d   = def_d,
+                        m_un    = m_un,
+                        stype   = stype,
+                        defpos  = defpos,
+                        m_def   = m_def,
+                        d_map   = d_map,
+                        modname = self.modname)
+            
+            self.st.out(union_register_at_module_scope,
+                        uname   = uname,
+                        modname = self.modname)
+        else:
+            self.st.out(union_descriptor,
+                        uname   = uname,
+                        m_to_d  = m_to_d,
+                        d_to_m  = d_to_m,
+                        def_m   = def_m,
+                        def_d   = def_d,
+                        m_un    = m_un,
+                        stype   = stype,
+                        defpos  = defpos,
+                        m_def   = m_def,
+                        d_map   = d_map,
+                        scope   = dotName(fscopedName[:-1]))
+            
+            self.st.out(union_register, uname = uname)
+
+    #
+    # Forward union
+    #
+    def visitUnionForward(self, node):
+        if self.handleImported(node): return
+
+        uname = mangle(node.identifier())
+
+        if self.at_module_scope:
+            self.st.out(forward_union_descr_at_module_scope,
+                        uname   = uname,
+                        repoId  = node.repoId(),
+                        modname = self.modname)
+        else:
+            self.st.out(forward_union_descr,
+                        uname   = uname,
+                        repoId  = node.repoId(),
+                        modname = self.modname)
+
+    #
+    # Enum
+    #
+    def visitEnum(self, node):
+        if self.handleImported(node): return
+
+        ename = mangle(node.identifier())
+        self.st.out(enum_start, ename = ename)
+
+        i=0
+        elist = []
+        for item in node.enumerators():
+            eval = str(i)
+
+            if self.at_module_scope:
+                self.st.out(enum_item_at_module_scope,
+                            item    = item.identifier(),
+                            eitem   = mangle(item.identifier()),
+                            eval    = eval,
+                            modname = self.modname)
+            else:
+                self.st.out(enum_item,
+                            item    = item.identifier(),
+                            eitem   = mangle(item.identifier()),
+                            eval    = eval)
+
+            if self.at_module_scope:
+                elist.append(dotName(fixupScopedName(item.scopedName())))
+            else:
+                elist.append(mangle(item.identifier()))
+
+            i = i + 1
+
+        eitems = string.join(elist, ", ")
+
+        if self.at_module_scope:
+            self.st.out(enum_object_and_descriptor_at_module_scope,
+                        ename   = ename,
+                        repoId  = node.repoId(),
+                        eitems  = eitems,
+                        modname = self.modname)
+        else:
+            self.st.out(enum_object_and_descriptor,
+                        ename   = ename,
+                        repoId  = node.repoId(),
+                        eitems  = eitems)
+
+    def visitNative(self, node):
+        if self.handleImported(node): return
+
+        sys.stderr.write(main.cmdname + \
+                         ": Warning: ignoring declaration of native " + \
+                         node.identifier() + "\n")
+
+    def visitValueForward(self, node):
+        if self.handleImported(node): return
+
+        vname = mangle(node.identifier())
+
+        self.st.out(value_forward_at_module_scope,
+                    vname=vname, repoId=node.repoId(), modname=self.modname)
+
+
+    def visitValueBox(self, node):
+        if self.handleImported(node): return
+
+        boxname = mangle(node.identifier())
+        boxdesc = typeToDescriptor(node.boxedType())
+
+        self.st.out(valuebox, boxname=boxname, repoId=node.repoId(),
+                    boxdesc=boxdesc, modname=self.modname)
+
+
+    def visitValueAbs(self, node):
+        if self.handleImported(node): return
+
+        vname = mangle(node.identifier())
+
+        fscopedName = fixupScopedName(node.scopedName(), "")
+        scopedname  = dotName(fscopedName)
+
+        if node.inherits():
+            inheritl = []
+            for i in node.inherits():
+                i = i.fullDecl()
+                inheritl.append(dotName(fixupScopedName(i.scopedName())))
+            
+            inherits = string.join(inheritl, ", ")
+        else:
+            inherits = "_0_CORBA.ValueBase"
+
+        self.st.out(valueabs_class,
+                    vname=vname, scopedname=scopedname, repoId=node.repoId(),
+                    inherits=inherits, modname=self.modname)
+
+        # Declarations within the value
+        if len(node.declarations()) > 0:
+            self.st.inc_indent()
+            self.at_module_scope = 0
+            self.currentScope.append(node.identifier())
+
+            for d in node.declarations():
+                d.accept(self)
+
+            self.currentScope.pop()
+            self.at_module_scope = 1
+            self.st.dec_indent()
+            self.st.out("")
+
+        basedesc = "_0_CORBA.tcInternal.tv_null"
+
+        self.st.out(value_descriptor_at_module_scope,
+                    vname=vname, modifier="_0_CORBA.VM_ABSTRACT",
+                    tbaseids="None", basedesc=basedesc, mdescs="",
+                    modname=self.modname)
+
+
+    def visitValue(self, node):
+        if self.handleImported(node): return
+
+        vname = mangle(node.identifier())
+
+        fscopedName = fixupScopedName(node.scopedName(), "")
+        scopedname  = dotName(fscopedName)
+
+        if node.inherits():
+            inheritl = []
+            for i in node.inherits():
+                i = i.fullDecl()
+                inheritl.append(dotName(fixupScopedName(i.scopedName())))
+            
+        else:
+            inheritl = ["_0_CORBA.ValueBase"]
+
+        skeleton_opl = []
+        for i in node.supports():
+            i = i.fullDecl()
+            sn = fixupScopedName(i.scopedName())
+            sn[0] = sn[0] + "__POA"
+            dn = dotName(sn)
+            inheritl.append(dn)
+            skeleton_opl.append(dn)
+
+        inherits = string.join(inheritl, ", ")
+
+        # Go up the chain of inherited interfaces, picking out the
+        # state members
+        members = []
+        ilist   = []
+        cnode   = node
+        
+        while 1:
+            cin = cnode.inherits()
+            if not cin:
+                break
+            i = cin[0].fullDecl()
+            if not isinstance(i, idlast.Value):
+                break
+            ilist.append(i)
+            cnode = i
+
+        ilist.reverse()
+        ilist.append(node)
+        
+        for i in ilist:
+            members.extend(i.statemembers())
+
+        set_argl = []
+
+        for i in range(len(members)):
+            member = members[i]
+            for d in member.declarators():
+                set_argl.append("self.%s = args[%d]" %
+                                (mangle(d.identifier()),i))
+
+        if set_argl:
+            set_args = string.join(set_argl, "\n")
+        else:
+            set_args = "pass"
+
+        if len(set_argl) == 1:
+            s = ""
+        else:
+            s = "s"
+
+        self.st.out(value_class,
+                    vname=vname, scopedname=scopedname, repoId=node.repoId(),
+                    inherits=inherits, set_args=set_args, arglen=len(set_argl),
+                    s=s, modname=self.modname)
+
+        # Declarations within the value
+        if len(node.declarations()) > 0:
+            self.st.inc_indent()
+            self.at_module_scope = 0
+            self.currentScope.append(node.identifier())
+
+            for d in node.declarations():
+                d.accept(self)
+
+            self.currentScope.pop()
+            self.at_module_scope = 1
+            self.st.dec_indent()
+            self.st.out("")
+
+        # Skeleton operation declarations if necessary
+        if node.supports():
+            self.st.out(skeleton_methodmap, methodmap="{}")
+            for i in skeleton_opl:
+                self.st.out(skeleton_inheritmap, inheritclass=i)
+
+            self.st.out(skeleton_set_skel, ifid=vname)
+
+        # Register factory if no callables or factories
+        register_factory = 1
+
+        if not all_factories:
+            cnode = node
+            while 1:
+                if cnode.callables() or cnode.factories() or cnode.supports():
+                    register_factory = 0
+                    break
+                cin = cnode.inherits()
+                if not cin:
+                    break
+                for n in cin:
+                    n = n.fullDecl()
+                    if not isinstance(n, idlast.Value):
+                        register_factory = 0
+                        break
+                cnode = cin[0].fullDecl()
+
+        if register_factory:
+            self.st.out(value_register_factory, vname=vname)
+        
+        # If value supports some interfaces, output an objref class for it
+        if node.supports():
+            inheritl = []
+            methodl  = []
+            for i in node.supports():
+                i = i.fullDecl()
+                sn = fixupScopedName(i.scopedName())
+                inheritl.append(dotName(sn[:-1] + ["_objref_" + sn[-1]]))
+                methodl.append(dotName(sn[:-1] + ["_objref_" + sn[-1]]) +
+                               ".__methods__")
+                
+            inherits = string.join(inheritl, ", ")
+
+            self.st.out(objref_class, ifid=vname, inherits=inherits)
+
+            for inclass in inheritl:
+                self.st.out(objref_inherit_init, inclass=inclass)
+
+            methods = string.join(methodl, " + ")
+            self.st.out(objref_methods, methods = methods)
+
+            # registerObjRef()
+            self.st.out(value_objref_register,
+                        ifid=vname, modname=self.modname)
+
+        # Modifier
+        if node.custom():
+            modifier = "_0_CORBA.VM_CUSTOM"
+        elif node.truncatable():
+            modifier = "_0_CORBA.VM_TRUNCATABLE"
+        else:
+            modifier = "_0_CORBA.VM_NONE"
+
+        # Truncatable bases
+        tbasel = []
+        cnode  = node
+        while 1:
+            cin = cnode.inherits()
+            if not cin:
+                break
+            i = cin[0]
+            i = i.fullDecl()
+            if not isinstance(i, idlast.Value):
+                break
+            if cnode.truncatable():
+                sn = fixupScopedName(i.scopedName())
+                tbasel.append(dotName(sn) + "._NP_RepositoryId")
+            else:
+                break
+            cnode = i
+
+        if tbasel:
+            tbaseids = "(%s._NP_RepositoryId, %s)" % (vname,
+                                                     string.join(tbasel, ", "))
+        else:
+            tbaseids = "None"
+
+        basedesc = None
+        if node.inherits():
+            i = node.inherits()[0].fullDecl()
+            if isinstance(i, idlast.Value):
+                sn = i.scopedName()[:]
+                sn[-1] = "_d_" + sn[-1]
+                basedesc = dotName(fixupScopedName(sn))
+
+        if basedesc is None:
+            basedesc = "_0_CORBA.tcInternal.tv_null"
+
+        mlist = []
+        for m in node.statemembers():
+            for d in m.declarators():
+                mlist.append('"%s"' % mangle(d.identifier()))
+                mlist.append(typeAndDeclaratorToDescriptor(m.memberType(),
+                                                           d, []))
+                if m.memberAccess() == 1:
+                    mlist.append("_0_CORBA.PRIVATE_MEMBER")
+                else:
+                    mlist.append("_0_CORBA.PUBLIC_MEMBER")
+                    
+        mdescs = string.join(mlist, ", ")
+        self.st.out(value_descriptor_at_module_scope,
+                    vname=vname, modifier=modifier, tbaseids=tbaseids,
+                    basedesc=basedesc, mdescs=mdescs, modname=self.modname)
+
+
+
+def docConst(node):
+    if isinstance(node, idlast.Const)        and \
+       node.constKind() == idltype.tk_string and \
+       node.identifier()[-7:] == "__doc__":
+        return node.identifier()[:-7]
+    else:
+        return None
+
+def nodeId(node):
+    if hasattr(node, "identifier"):
+        return node.identifier()
+    else:
+        return None
+
+def docWarning(node):
+    sys.stderr.write(main.cmdname + \
+                     ": Warning: Constant '" + node.identifier() + "' looks "
+                     "like a Python docstring, but there is no declaration "
+                     "named '" + node.identifier()[:-7] + "'.\n")
+    
+class DocstringVisitor (idlvisitor.AstVisitor):
+    def __init__(self, st):
+        self.docs = []
+        self.st   = st
+
+    def output(self):
+        if self.docs:
+            self.st.out("""\
+#
+# Docstrings
+#
+""")
+        for nsn, dsn in self.docs:
+            nsn = fixupScopedName(nsn)
+            dsn = fixupScopedName(dsn)
+
+            self.st.out("@node@.__doc__ = @doc@",
+                        node=dotName(nsn), doc=dotName(dsn))
+            
+        if self.docs:
+            self.st.out("")
+
+    def visitAST(self, node):
+        for n in node.declarations():
+            if not output_inline and not n.mainFile(): continue
+            
+            d = docConst(n)
+            if d:
+                ok = 0
+                for o in node.declarations():
+                    if nodeId(o) == d:
+                        self.docs.append((o.scopedName(), n.scopedName()))
+                        if isinstance(o, idlast.Interface):
+                            sn = o.scopedName()[:]
+                            sn[-1] = "_objref_" + sn[-1]
+                            self.docs.append((sn, n.scopedName()))
+                        ok = 1
+                        break
+                if not ok:
+                    docWarning(n)
+            n.accept(self)
+
+    def visitModule(self, node):
+        for n in node.definitions():
+            d = docConst(n)
+            if d:
+                if d == node.identifier():
+                    self.docs.append((node.scopedName(), n.scopedName()))
+                else:
+                    ok = 0
+                    for o in node.definitions():
+                        if nodeId(o) == d:
+                            self.docs.append((o.scopedName(), n.scopedName()))
+                            if isinstance(o, idlast.Interface):
+                                sn = o.scopedName()[:]
+                                sn[-1] = "_objref_" + sn[-1]
+                                self.docs.append((sn, n.scopedName()))
+                            ok = 1
+                            break
+                    if not ok:
+                        docWarning(n)
+            n.accept(self)
+
+    def visitInterface(self, node):
+        for n in node.declarations():
+            d = docConst(n)
+            if d:
+                if d == node.identifier():
+                    self.docs.append((node.scopedName(), n.scopedName()))
+                    sn = node.scopedName()[:]
+                    sn[-1] = "_objref_" + sn[-1]
+                    self.docs.append((sn, n.scopedName()))
+                else:
+                    ok = 0
+                    for o in node.declarations():
+                        if nodeId(o) == d:
+                            self.docs.append((o.scopedName(), n.scopedName()))
+                            ok = 1
+                            break
+                                
+                    if ok:
+                        continue
+
+                    for o in node.callables():
+                        self.target_id   = d
+                        self.target_node = n
+                        self.ok          = 0
+                        o.accept(self)
+                        if self.ok:
+                            break
+                    
+                    if not self.ok:    
+                        docWarning(n)
+
+    def visitOperation(self, node):
+        if node.identifier() == self.target_id:
+            sn = node.scopedName() + ["im_func"]
+            sn[-3] = "_objref_" + sn[-3]
+            self.docs.append((sn, self.target_node.scopedName()))
+            self.ok = 1
+
+    def visitAttribute(self, node):
+        for n in node.declarators():
+            if n.identifier() == self.target_id:
+                sn = n.scopedName() + ["im_func"]
+                sn[-3] = "_objref_" + sn[-3]
+                sn[-2] = "_get_"    + sn[-2]
+                self.docs.append((sn, self.target_node.scopedName()))
+                if not node.readonly():
+                    sn = sn[:]
+                    sn[-2] = "_set_" + n.identifier()
+                    self.docs.append((sn, self.target_node.scopedName()))
+                self.ok = 1
+
+
+class ExampleVisitor (idlvisitor.AstVisitor, idlvisitor.TypeVisitor):
+    def __init__(self, st):
+        self.st = st
+        self.first = None
+
+    def visitAST(self, node):
+        for n in node.declarations():
+            if not output_inline and not n.mainFile(): continue
+
+            if isinstance(n, idlast.Module) or isinstance(n, idlast.Interface):
+                n.accept(self)
+
+    def visitModule(self, node):
+        for n in node.definitions():
+            if not output_inline and not n.mainFile(): continue
+
+            if isinstance(n, idlast.Module) or isinstance(n, idlast.Interface):
+                n.accept(self)
+
+    def visitInterface(self, node):
+        ifname = mangle(node.identifier())
+        sname  = node.scopedName()
+        ccname = idlutil.ccolonName(sname)
+        fsname = fixupScopedName(sname, prefix="")
+        dname  = dotName(fsname)
+        skname = skeletonModuleName(dname)
+
+        if self.first is None:
+            self.first = ifname
+
+        if len(node.inherits()) == 1:
+            inheritance_note = """
+    # Note: this interface inherits from another interface. You must
+    # either multiply inherit from the servant class implementing the
+    # base interface, or explicitly implement the inherited operations
+    # here.
+    #
+    # Inherited interface:
+    #
+"""
+        elif node.inherits():
+            inheritance_note = """
+    # Note: this interface inherits from other interfaces. You must either
+    # multiply inherit from the servant classes implementing the base
+    # interfaces, or explicitly implement the inherited operations here.
+    #
+    # Inherited interfaces:
+    #
+"""
+        else:
+            inheritance_note = ""
+
+        for inh in node.inherits():
+            iname = idlutil.ccolonName(inh.fullDecl().scopedName())
+            inheritance_note = inheritance_note + "    #   %s\n" % iname
+        
+        self.st.out(example_classdef, ifname=ifname,
+                    ccname=ccname, skname=skname,
+                    inheritance_note = inheritance_note)
+
+        for c in node.callables():
+
+            if isinstance(c, idlast.Attribute):
+
+                c.attrType().accept(self)
+                attrtype = self.__result_type
+
+                for attr in c.identifiers():
+
+                    signature = "attribute %s %s" % (attrtype, attr)
+
+                    if c.readonly():
+                        signature = "readonly " + signature
+
+                    if not c.readonly():
+                        self.st.out(example_opdef,
+                                    signature = signature,
+                                    opname = "_set_" + attr,
+                                    args = ", value",
+                                    returnspec = "None")
+
+                    self.st.out(example_opdef,
+                                signature = signature,
+                                opname = "_get_" + attr,
+                                args = "",
+                                returnspec = "attribute value")
+            else:
+                # Operation
+                innames  = []
+                outnames = []
+                siglist  = []
+
+                c.returnType().accept(self)
+                rettype = self.__result_type
+
+                if c.returnType().kind() != idltype.tk_void:
+                    outnames.append("result")
+
+                for p in c.parameters():
+                    if p.is_in():
+                        innames.append(p.identifier())
+                    if p.is_out():
+                        outnames.append(p.identifier())
+
+                    direction = {0:"in", 1:"out", 2:"inout"}[p.direction()]
+
+                    p.paramType().accept(self)
+                    siglist.append("%s %s %s" % (direction,
+                                                 self.__result_type,
+                                                 p.identifier()))
+
+                signature = "%s %s(%s)" % (rettype, c.identifier(),
+                                           string.join(siglist, ", "))
+
+                if innames:
+                    args = ", " + string.join(innames, ", ")
+                else:
+                    args = ""
+
+                if outnames:
+                    returnspec = string.join(outnames, ", ")
+                else:
+                    returnspec = "None"
+
+                self.st.out(example_opdef,
+                            signature = signature,
+                            opname = c.identifier(),
+                            args = args,
+                            returnspec = returnspec)
+
+
+
+    ttsMap = {
+        idltype.tk_void:       "void",
+        idltype.tk_short:      "short",
+        idltype.tk_long:       "long",
+        idltype.tk_ushort:     "unsigned short",
+        idltype.tk_ulong:      "unsigned long",
+        idltype.tk_float:      "float",
+        idltype.tk_double:     "double",
+        idltype.tk_boolean:    "boolean",
+        idltype.tk_char:       "char",
+        idltype.tk_octet:      "octet",
+        idltype.tk_any:        "any",
+        idltype.tk_TypeCode:   "CORBA::TypeCode",
+        idltype.tk_Principal:  "CORBA::Principal",
+        idltype.tk_longlong:   "long long",
+        idltype.tk_ulonglong:  "unsigned long long",
+        idltype.tk_longdouble: "long double",
+        idltype.tk_wchar:      "wchar"
+        }
+
+    def visitBaseType(self, type):
+        self.__result_type = self.ttsMap[type.kind()]
+
+    def visitStringType(self, type):
+        if type.bound() == 0:
+            self.__result_type = "string"
+        else:
+            self.__result_type = "string<" + str(type.bound()) + ">"
+
+    def visitWStringType(self, type):
+        if type.bound() == 0:
+            self.__result_type = "wstring"
+        else:
+            self.__result_type = "wstring<" + str(type.bound()) + ">"
+
+
+    def visitDeclaredType(self, type):
+        self.__result_type = idlutil.ccolonName(type.decl().scopedName())
+
+
+
+
+
+def operationToDescriptors(op):
+    """Return the descriptors for an operation.
+
+    Returns a tuple containing strings of (in descriptor, out
+    descriptor, exception map, context list, contains values)
+    """
+
+    indl  = []
+    outdl = []
+    cv    = 0
+
+    if op.returnType() is not None and \
+       op.returnType().kind() != idltype.tk_void:
+
+        outdl.append(typeToDescriptor(op.returnType()))
+        cv = idltype.containsValueType(op.returnType())
+
+    # Make the lists of in and out parameters
+    for p in op.parameters():
+
+        if p.is_in():
+            indl.append(typeToDescriptor(p.paramType()))
+        if p.is_out():
+            outdl.append(typeToDescriptor(p.paramType()))
+
+        cv = cv or idltype.containsValueType(p.paramType())
+
+    # Fudge single-item lists so that single item tuples work
+    if len(indl)  == 1: indl.append("")
+    if len(outdl) == 1: outdl.append("")
+
+    inds = "(" + string.join(indl, ", ") + ")"
+    if op.oneway():
+        outds = "None"
+    else:
+        outds = "(" + string.join(outdl, ", ") + ")"
+
+    # Exceptions
+    excl = []
+
+    for e in op.raises():
+        sn = fixupScopedName(e.scopedName())
+        ename = dotName(sn)
+        edesc = dotName(sn[:-1] + [ "_d_" + sn[-1]])
+        excl.append(ename + "._NP_RepositoryId: " + edesc)
+
+    if len(excl) > 0:
+        excs = "{" + string.join(excl, ", ") + "}"
+    else:
+        excs = "None"
+
+    if op.contexts():
+        ctxts = "[" + string.join(map(repr, op.contexts()), ", ") + "]"
+    else:
+        ctxts = None
+
+    return inds, outds, excs, ctxts, cv
+
+
+
+ttdMap = {
+    idltype.tk_short:      "omniORB.tcInternal.tv_short",
+    idltype.tk_long:       "omniORB.tcInternal.tv_long",
+    idltype.tk_ushort:     "omniORB.tcInternal.tv_ushort",
+    idltype.tk_ulong:      "omniORB.tcInternal.tv_ulong",
+    idltype.tk_float:      "omniORB.tcInternal.tv_float",
+    idltype.tk_double:     "omniORB.tcInternal.tv_double",
+    idltype.tk_boolean:    "omniORB.tcInternal.tv_boolean",
+    idltype.tk_char:       "omniORB.tcInternal.tv_char",
+    idltype.tk_octet:      "omniORB.tcInternal.tv_octet",
+    idltype.tk_any:        "omniORB.tcInternal.tv_any",
+    idltype.tk_TypeCode:   "omniORB.tcInternal.tv_TypeCode",
+    idltype.tk_Principal:  "omniORB.tcInternal.tv_Principal",
+    idltype.tk_longlong:   "omniORB.tcInternal.tv_longlong",
+    idltype.tk_ulonglong:  "omniORB.tcInternal.tv_ulonglong",
+    idltype.tk_wchar:      "omniORB.tcInternal.tv_wchar"
+}
+
+unsupportedMap = {
+    idltype.tk_longdouble: "long double",
+}
+
+def typeToDescriptor(tspec, from_scope=[], is_typedef=0):
+    if hasattr(tspec, "python_desc"):
+        return tspec.python_desc
+
+    if ttdMap.has_key(tspec.kind()):
+        tspec.python_desc = ttdMap[tspec.kind()]
+        return tspec.python_desc
+
+    if unsupportedMap.has_key(tspec.kind()):
+        error_exit("omniORBpy does not support the %s type." %
+                   unsupportedMap[tspec.kind()])
+
+    if tspec.kind() == idltype.tk_string:
+        ret = "(omniORB.tcInternal.tv_string," + str(tspec.bound()) + ")"
+
+    elif tspec.kind() == idltype.tk_wstring:
+        ret = "(omniORB.tcInternal.tv_wstring," + str(tspec.bound()) + ")"
+
+    elif tspec.kind() == idltype.tk_sequence:
+        ret = "(omniORB.tcInternal.tv_sequence, " + \
+              typeToDescriptor(tspec.seqType(), from_scope) + \
+              ", " + str(tspec.bound()) + ")"
+
+    elif tspec.kind() == idltype.tk_fixed:
+        ret = "(omniORB.tcInternal.tv_fixed, " + \
+              str(tspec.digits()) + ", " + str(tspec.scale()) + ")"
+
+    elif tspec.kind() == idltype.tk_alias:
+        sn = fixupScopedName(tspec.scopedName())
+        if is_typedef:
+            return 'omniORB.typeCodeMapping["%s"]._d' % tspec.decl().repoId()
+        else:
+            return 'omniORB.typeMapping["%s"]' % tspec.decl().repoId()
+
+    else:
+        ret = 'omniORB.typeMapping["%s"]' % tspec.decl().repoId()
+
+    tspec.python_desc = ret
+    return ret
+
+
+def typeAndDeclaratorToDescriptor(tspec, decl, from_scope, is_typedef=0):
+    desc = typeToDescriptor(tspec, from_scope, is_typedef)
+
+    if len(decl.sizes()) > 0:
+        sizes = decl.sizes()[:]
+        sizes.reverse()
+        for size in sizes:
+            desc = "(omniORB.tcInternal.tv_array, " + \
+                   desc + ", " + str(size) + ")"
+    return desc
+
+def skeletonModuleName(mname):
+    """Convert a scoped name string into the corresponding skeleton
+module name. e.g. M1.M2.I -> M1__POA.M2.I"""
+    l = string.split(mname, ".")
+    l[0] = l[0] + "__POA"
+    return string.join(l, ".")
+
+def dotName(scopedName, our_scope=[]):
+    if scopedName[:len(our_scope)] == our_scope:
+        l = map(mangle, scopedName[len(our_scope):])
+    else:
+        l = map(mangle, scopedName)
+    return string.join(l, ".")
+
+def mangle(name):
+    if keyword.iskeyword(name): return "_" + name
+
+    # None is a pseudo-keyword that cannot be assigned to.
+    if name == "None": return "_None"
+
+    return name
+
+def fixupScopedName(scopedName, prefix="_0_"):
+    """Add a prefix and _GlobalIDL to the front of a ScopedName if necessary"""
+
+    try:
+        decl = idlast.findDecl([scopedName[0]])
+    except idlast.DeclNotFound:
+        decl = None
+
+    if isinstance(decl, idlast.Module):
+        scopedName = [prefix + mangle(scopedName[0])] + scopedName[1:]
+    else:
+        scopedName = [prefix + global_module] + scopedName
+    return scopedName
+
+def valueToString(val, kind, scope=[]):
+    if kind == idltype.tk_enum:
+        return dotName(fixupScopedName(val.scopedName()), scope)
+
+    elif kind in [idltype.tk_string, idltype.tk_char]:
+        return '"' + idlutil.escapifyString(val) + '"'
+
+    elif kind == idltype.tk_wstring:
+        return 'u"' + idlutil.escapifyWString(val) + '"'
+
+    elif kind == idltype.tk_wchar:
+        return 'u"' + idlutil.escapifyWString([val]) + '"'
+
+    elif kind == idltype.tk_long and val == -2147483647 - 1:
+        return "-2147483647 - 1"
+
+    elif kind in [idltype.tk_float, idltype.tk_double, idltype.tk_longdouble]:
+        return idlutil.reprFloat(val)
+
+    elif kind == idltype.tk_fixed:
+        return "CORBA.fixed('" + val + "')"
+
+    else:
+        return str(val)
+
+__translate_table = string.maketrans(" -.,", "____")
+
+def outputFileName(idlname):
+    global __translate_table
+    return string.translate(os.path.basename(idlname), __translate_table)
+
+def checkStubPackage(package):
+    """Check the given package name for use as a stub directory
+
+    Make sure all fragments of the package name are directories, or
+    create them. Make __init__.py files in all directories."""
+
+    if len(package) == 0:
+        return
+
+    if package[-1] == ".":
+        package = package[:-1]
+
+    path = ""
+    for name in string.split(package, "."):
+        path = os.path.join(path, name)
+        
+        if os.path.exists(path):
+            if not os.path.isdir(path):
+                error_exit('Output error: "%s" exists and is not '
+                           'a directory.' % path)
+        else:
+            try:
+                os.mkdir(path)
+            except:
+                error_exit('Cannot create directory "%s".\n' % path)
+
+        initfile = os.path.join(path, "__init__.py")
+
+        if os.path.exists(initfile):
+            if not os.path.isfile(initfile):
+                error_exit('Output error: "%s" exists and is not a file.' %
+                           initfile)
+        else:
+            try:
+                open(initfile, "w").write("# omniORB stub directory\n")
+            except:
+                error_exit('Cannot create "%s".' % initfile)
+
+
+def updateModules(modules, pymodule):
+    """Create or update the Python modules corresponding to the IDL
+    module names"""
+
+    checkStubPackage(module_package)
+
+    poamodules = map(skeletonModuleName, modules)
+
+    real_updateModules(modules,    pymodule)
+    real_updateModules(poamodules, pymodule)
+
+
+def real_updateModules(modules, pymodule):
+
+    for module in modules:
+        modlist = string.split(module_package, ".") + string.split(module, ".")
+        modpath = apply(os.path.join, modlist)
+        modfile = os.path.join(modpath, "__init__.py")
+        tmpfile = os.path.join(modpath, "new__init__.py")
+
+        if not os.path.exists(modpath):
+            try:
+                os.makedirs(modpath)
+            except:
+                error_exit('Cannot create path "%s".' % modpath)
+
+        # Make the __init__.py file if it does not already exist
+        if not os.path.exists(modfile):
+            try:
+                f = open(modfile, "w")
+            except:
+                error_exit('Cannot create "%s".' % modfile)
+            
+            st = output.Stream(f, 4)
+
+            st.out(pymodule_template, module=module, package=module_package)
+
+            f.close()
+            del f, st
+
+        if not os.path.isfile(modfile):
+            error_exit('Output error: "%s" exists but is not a file.' %
+                       modfile)
+
+        # Insert the import line for the current IDL file
+        try:
+            inf = open(modfile, "r")
+        except:
+            error_exit('Cannot open "%s" for reading.' % modfile)
+
+        try:
+            outf = open(tmpfile, "w")
+        except:
+            error_exit('Cannot open "%s" for writing.' % tmpfile)
+
+        line = ""
+        while line[:7] != "# ** 1.":
+            line = inf.readline()
+            if line == "":
+                error_exit('Output error: "%s" ended before I found a '
+                           '"# ** 1." tag.\n'
+                           'Have you left behind some files from a '
+                           'different Python ORB?' % modfile)
+                
+            outf.write(line)
+            
+        already    = 0
+        outputline = "import " + pymodule + "\n"
+
+        while line != "\n":
+            line = inf.readline()
+            if line == "":
+                error_exit('Output error: "%s" ended while I was '
+                           'looking at imports.' % modfile)
+
+            if line != "\n":
+                outf.write(line)
+                if line == outputline:
+                    already = 1
+
+        if not already:
+            outf.write(outputline)
+
+        outf.write("\n")
+
+        # Output the rest of the file
+        while line != "":
+            line = inf.readline()
+            outf.write(line)
+
+        inf.close()
+        outf.close()
+
+        try:
+            os.remove(modfile)
+        except:
+            error_exit('Cannot remove "%s".' % modfile)
+        try:
+            os.rename(tmpfile, modfile)
+        except:
+            error_exit('Cannot rename "%s" to "%s".' % (tmpfile, modfile))
+
+    # Go round again, importing sub-modules from their parent modules
+    for module in modules:
+        modlist = string.split(module, ".")
+
+        if len(modlist) == 1:
+            continue
+
+        modlist = string.split(module_package, ".") + modlist
+        submod  = modlist[-1]
+        modpath = apply(os.path.join, modlist[:-1])
+        modfile = os.path.join(modpath, "__init__.py")
+        tmpfile = os.path.join(modpath, "new__init__.py")
+
+        # Insert the import line for the sub-module
+        try:
+            inf = open(modfile, "r")
+        except:
+            error_exit('Cannot open "%s" for reading.' % modfile)
+
+        try:
+            outf = open(tmpfile, "w")
+        except:
+            error_exit('Cannot open "%s" for writing.' % tmpfile)
+
+        line = ""
+        while line[:7] != "# ** 2.":
+            line = inf.readline()
+            if line == "":
+                error_exit('Output error: "%s" ended before I found a '
+                           '"# ** 1." tag.\n'
+                           'Have you left behind some files from a '
+                           'different Python ORB?' % modfile)
+                
+            outf.write(line)
+            
+        already    = 0
+        outputline = "import " + submod + "\n"
+
+        while line != "\n":
+            line = inf.readline()
+            if line == "":
+                error_exit('Output error: "%s" ended while I was '
+                           'looking at imports.' % modfile)
+
+            if line != "\n":
+                outf.write(line)
+                if line == outputline:
+                    already = 1
+
+        if not already:
+            outf.write(outputline)
+
+        outf.write("\n")
+
+        # Output the rest of the file
+        while line != "":
+            line = inf.readline()
+            outf.write(line)
+
+        inf.close()
+        outf.close()
+
+        try:
+            os.remove(modfile)
+        except:
+            error_exit('Cannot remove "%s".' % modfile)
+        try:
+            os.rename(tmpfile, modfile)
+        except:
+            error_exit('Cannot rename "%s" to "%s".' % (tmpfile, modfile))
diff --git a/idl/vtkWrapIDL.c b/idl/vtkWrapIDL.c
new file mode 100644 (file)
index 0000000..6e8aa07
--- /dev/null
@@ -0,0 +1,1566 @@
+// PARAVIS : ParaView wrapper SALOME module
+//
+// Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
+// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License.
+//
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+// File   : vtkWrapIDL.c
+// Author : Vladimir TURIN
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+#include "vtkParse.h"
+#include "vtkWrapIDL.h"
+
+char* Copyright[] = {
+  "// Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,",
+  "// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS",
+  "//",
+  "// This library is free software; you can redistribute it and/or",
+  "// modify it under the terms of the GNU Lesser General Public",
+  "// License as published by the Free Software Foundation; either",
+  "// version 2.1 of the License.",
+  "//",
+  "// This library is distributed in the hope that it will be useful,",
+  "// but WITHOUT ANY WARRANTY; without even the implied warranty of",
+  "// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU",
+  "// Lesser General Public License for more details.",
+  "//",
+  "// You should have received a copy of the GNU Lesser General Public",
+  "// License along with this library; if not, write to the Free Software",
+  "// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA",
+  "//",
+  "// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com",
+  ""
+};
+
+#define bs 8192
+
+int numberOfWrappedFunctions = 0;
+FunctionInfo *wrappedFunctions[1000];
+extern FunctionInfo *currentFunction;
+
+static void add_to_sig(char *sig, const char *add, int *i)
+{
+  strcpy(&sig[*i],add);
+  *i += (int)strlen(add);
+}
+
+int IsReturnArg(int I) {
+  return (I == MAX_ARGS);
+}
+
+void AddReturnArg(char *Result, int *CurrPos) {
+  add_to_sig(Result,"virtual ",CurrPos);
+}
+
+void AddNotReturnArg(int Type, char *Result, int *CurrPos) {
+#if defined(IDL_I_HH) || defined(IDL_I_CC)
+  ;
+#else
+  if(IsIn(Type))
+    add_to_sig(Result,"in ",CurrPos);
+  else
+    add_to_sig(Result,"inout ",CurrPos);
+#endif
+}
+
+int IsFunction(int Type) {
+  return (Type == 0x5000);
+}
+
+int IsConst(int Type) {
+  return ((Type % 0x2000) >= 0x1000);
+}
+
+void AddConst(char *Result, int *CurrPos) {
+#if defined(IDL_I_HH) || defined(IDL_I_CC)
+  add_to_sig(Result,"const ",CurrPos);
+#else
+  add_to_sig(Result,"in ",CurrPos);
+#endif
+}
+
+int IsPtr(int Type) {
+  return ((Type % 0x1000)/0x100 == 0x1);
+}
+
+int IsIn(int Type) {
+  return 1;
+  //return ((Type % 0x1000)/0x100 < 1 || (Type % 0x1000)/0x100 > 7);
+}
+
+int IsUnknown(int Type) {
+  return ((Type % 0x1000)/0x100 == 0x8);
+}
+
+void AddAtomArg(int I, int Type, char *TypeIDL, char *TypeCorba, char *Result, int *CurrPos) {
+#if defined(IDL_I_HH) || defined(IDL_I_CC)
+  add_to_sig(Result,"CORBA::",CurrPos);
+  add_to_sig(Result,TypeCorba,CurrPos);
+
+  if (!IsReturnArg(I) && !IsConst(Type) && !IsIn(Type))
+    add_to_sig(Result,"&",CurrPos);
+#else
+  add_to_sig(Result,TypeIDL,CurrPos);
+#endif
+  add_to_sig(Result," ",CurrPos);
+}
+
+int IsArray(int Type) {
+  return ((Type % 0x1000)/0x100 == 0x3);
+}
+
+void AddArrayArg(int I, int Type, char *TypeIDL, char *Result, int *CurrPos) {
+#if defined(IDL_I_HH) || defined(IDL_I_CC)
+  if(!IsReturnArg(I) && !IsConst(Type))
+    add_to_sig(Result, "const ",CurrPos);
+#endif
+  add_to_sig(Result, TypeIDL,CurrPos);
+  add_to_sig(Result, "_array",CurrPos);
+#if defined(IDL_I_HH) || defined(IDL_I_CC)
+  if(IsReturnArg(I)) {
+    add_to_sig(Result, "*",CurrPos);
+  } else {
+    add_to_sig(Result, "&",CurrPos);
+  }
+#else
+#endif
+  add_to_sig(Result, " ",CurrPos);
+}
+
+int IsBoolean(int Type) {
+  return ((Type % 0x10) == 0xE);
+}
+
+void AddBooleanAtomArg(int I, int Type, char *Result, int *CurrPos) {
+  AddAtomArg(I,Type,"boolean","Boolean",Result,CurrPos);
+}
+
+int IsChar(int Type) {
+  return ((Type % 0x10) == 0x3 || (Type % 0x10) == 0xD);
+}
+
+void AddCharAtomArg(int I, int Type, char *Result, int *CurrPos) {
+  AddAtomArg(I,Type,"char","Char",Result,CurrPos);
+}
+
+int IsString(Type) {
+  return (IsChar(Type) && IsArray(Type));
+}
+
+void AddStringArg(int I, char *Result, int *CurrPos) {
+#if defined(IDL_I_HH) || defined(IDL_I_CC)
+  add_to_sig(Result,"char ",CurrPos);
+#else
+  add_to_sig(Result,"string ",CurrPos);
+#endif
+}
+
+int IsFloat(int Type) {
+  return ((Type % 0x10) == 0x1);
+}
+
+void AddFloatAtomArg(int I, int Type, char *Result, int *CurrPos) {
+  AddAtomArg(I,Type,"float","Float",Result,CurrPos);
+}
+
+int IsFloatArray(int Type) {
+  return (IsFloat(Type) && IsArray(Type));
+}
+
+void AddFloatArrayArg(int I, int Type, char *Result, int *CurrPos) {
+  AddArrayArg(I,Type,"float",Result,CurrPos);
+}
+
+int IsDouble(int Type) {
+  return ((Type % 0x10) == 0x7);
+}
+
+void AddDoubleAtomArg(int I, int Type, char *Result, int *CurrPos) {
+  AddAtomArg(I,Type,"double","Double",Result,CurrPos);
+}
+
+int IsDoubleArray(int Type) {
+  return (IsDouble(Type) && IsArray(Type));
+}
+
+void AddDoubleArrayArg(int I, int Type, char *Result, int *CurrPos) {
+  AddArrayArg(I,Type,"double",Result,CurrPos);
+}
+
+int IsvtkIdType(int Type) {
+  return((Type % 0x10) == 0xA);
+}
+
+int IsShort(int Type) {
+  return ((Type % 0x10) == 0x4 || (Type % 0x10) == 0x5 || (Type % 0x10) == 0xA);
+}
+
+void AddShortAtomArg(int I, int Type, char *Result, int *CurrPos) {
+  AddAtomArg(I,Type,"short","Short",Result,CurrPos);
+}
+
+int IsShortArray(int Type) {
+  return (IsShort(Type) && IsArray(Type));
+}
+
+void AddShortArrayArg(int I, int Type, char *Result, int *CurrPos) {
+  AddArrayArg(I,Type,"short",Result,CurrPos);
+}
+
+int IsLong(int Type) {
+  return ((Type % 0x10) == 0x6 || (Type % 0x10) == 0xB || (Type % 0x10) == 0xC);
+}
+
+void AddLongAtomArg(int I, int Type, char *Result, int *CurrPos) {
+  AddAtomArg(I,Type,"long","Long",Result,CurrPos);
+}
+
+int IsLongArray(int Type) {
+  return (IsLong(Type) && IsArray(Type));
+}
+
+void AddLongArrayArg(int I, int Type, char *Result, int *CurrPos) {
+  AddArrayArg(I,Type,"long",Result,CurrPos);
+}
+
+int IsClass(int Type) {
+  return ((Type % 0x10) == 0x9);
+}
+
+void AddClassArg(int I, int Type, char *Class, char *Result, int *CurrPos) {
+#if defined(IDL_I_HH) || defined(IDL_I_CC)
+  add_to_sig(Result,"PARAVIS_Base",CurrPos);
+  if(IsReturnArg(I) || IsConst(Type) || IsIn(Type)) {
+    add_to_sig(Result,"_ptr",CurrPos);
+  } else {
+    add_to_sig(Result,"_ptr&",CurrPos);
+  }
+  add_to_sig(Result," ",CurrPos);
+#else
+  add_to_sig(Result,"PARAVIS_Base ",CurrPos);
+#endif
+}
+
+int _IsVoid(int Type) {
+  return ((Type % 0x10) == 0x2);
+}
+
+int IsVoid(int Type) {
+  return (_IsVoid(Type) && (!IsPtr(Type)));
+}
+
+void AddVoid(char *Result, int *CurrPos) {
+  add_to_sig(Result,"void ",CurrPos);
+}
+
+int IsVoidPtr(int Type) {
+  return (_IsVoid(Type) && (IsPtr(Type) || IsArray(Type)));
+}
+
+void AddVoidArg(int I, char *Result, int *CurrPos, int Type) {
+#if defined(IDL_I_HH) || defined(IDL_I_CC)
+  if(!IsReturnArg(I)) {
+    if(!IsConst(Type))
+      add_to_sig(Result,"const ",CurrPos);
+    add_to_sig(Result,"CORBA::Any& ",CurrPos);
+  } else {
+    add_to_sig(Result,"CORBA::Any ",CurrPos);
+  }
+#else
+  add_to_sig(Result,"any ",CurrPos);
+#endif
+}
+
+void AddTypeArray(int Type, char *Result, int *CurrPos) {
+  if(IsShort(Type))
+    add_to_sig(Result,"short",CurrPos);
+  if(IsLong(Type))
+    add_to_sig(Result,"long",CurrPos);
+  if(IsFloat(Type))
+    add_to_sig(Result,"float",CurrPos);
+  if(IsDouble(Type))
+    add_to_sig(Result,"double",CurrPos);
+  add_to_sig(Result,"_array",CurrPos);
+}
+
+typedef struct _ReadFuncs
+{
+  char* Name;
+  char* Signature;
+  int   EndPos;
+  int   NumPos;
+} ReadFuncs;
+
+ReadFuncs readFunctions[1000];
+int numberOfReadFunctions = 0;
+
+static int class_has_new = 0;
+
+void output_type(char* result, int *currPos, int i, int aType, char *Id)
+{
+  if(IsFloat(aType)) {
+    if(IsArray(aType)) {
+      add_to_sig(result,"float",currPos);
+    } else {
+      add_to_sig(result,"CORBA::Float",currPos);
+    }
+  }
+  
+  if(IsDouble(aType)) {
+    if(IsArray(aType)) {
+      add_to_sig(result,"double",currPos);
+    } else {
+      add_to_sig(result,"CORBA::Double",currPos);
+    }
+  }
+  
+  if(IsShort(aType)) {
+    if(IsArray(aType)) {
+      if(IsvtkIdType(aType)) {
+       add_to_sig(result,"vtkIdType",currPos);
+      } else {
+       add_to_sig(result,"int",currPos);
+      }
+    } else {
+      add_to_sig(result,"CORBA::Short",currPos);
+    }
+  }
+  
+  if(IsLong(aType)) {
+    if(IsArray(aType)) {
+      add_to_sig(result,"long",currPos);
+    } else {
+      add_to_sig(result,"CORBA::Long",currPos);
+    }
+  }
+  
+  if(IsChar(aType)) {
+    if(IsString(aType)) {
+      if(IsReturnArg(i))
+       add_to_sig(result,"const ",currPos);
+      add_to_sig(result,"char",currPos);
+    } else {
+      add_to_sig(result,"CORBA::Char",currPos);            
+    }
+  }
+
+  if(IsBoolean(aType)) {
+    add_to_sig(result,"CORBA::Boolean",currPos);
+  }
+  
+  if(IsVoidPtr(aType)) {
+    add_to_sig(result,"void",currPos);
+  }
+  
+  if(IsClass(aType)) {
+    add_to_sig(result,"::",currPos);
+    add_to_sig(result,Id,currPos);
+  }
+  
+  if(IsArray(aType) || IsPtr(aType) || IsClass(aType) || IsString(aType)) {
+    add_to_sig(result,"*",currPos);
+  }
+}
+
+void output_typedef(char* result, int *currPos, int i, int aType, char *Id)
+{
+  add_to_sig(result,"  typedef ",currPos);
+  output_type(result,currPos,i,aType,Id);
+}
+
+void output_temp(char* result, int *currPos, int i, int aType, char *Id, int aCount)
+{
+  static char buf[bs];
+
+  /* handle VAR FUNCTIONS */
+  if (IsFunction(aType)) {
+    return;
+  }
+
+#if defined(IDL_I_HH)
+  if(IsReturnArg(i)) {
+    AddReturnArg(result,currPos);
+  }
+#endif
+
+  if (IsReturnArg(i) && IsVoid(aType) && !IsVoidPtr(aType)) {
+    AddVoid(result,currPos);
+    return;
+  }
+
+  /* for const * return types prototype with const */
+  if ( IsConst(aType) || IsString(aType)) {
+    if(!IsReturnArg(i))        {
+      AddConst(result,currPos);
+    }
+  } else {
+    if(!IsReturnArg(i))        {
+      AddNotReturnArg(aType,result,currPos);
+    }
+  }
+
+  if(IsFloat(aType)) {
+    if(IsFloatArray(aType)) {
+      AddFloatArrayArg(i,aType,result,currPos);
+    } else {
+      AddFloatAtomArg(i,aType,result,currPos);
+    }
+  }
+  
+  if(IsDouble(aType)) {
+    if(IsDoubleArray(aType)) {
+      AddDoubleArrayArg(i,aType,result,currPos);
+    } else {
+      AddDoubleAtomArg(i,aType,result,currPos);
+    }
+  }
+
+  if(IsShort(aType)) {
+    if(IsShortArray(aType)) {
+      AddShortArrayArg(i,aType,result,currPos);
+    } else {
+      AddShortAtomArg(i,aType,result,currPos);
+    }
+  }
+
+  if(IsLong(aType)) {
+    if(IsLongArray(aType)) {
+      AddLongArrayArg(i,aType,result,currPos);
+    } else {
+      AddLongAtomArg(i,aType,result,currPos);
+    }
+  }
+
+  if(IsChar(aType)) {
+    if(IsString(aType)) {
+      AddStringArg(i,result,currPos);
+    } else {
+      AddCharAtomArg(i,aType,result,currPos);
+    }
+  }
+
+  if(IsBoolean(aType)) {
+    AddBooleanAtomArg(i,aType,result,currPos);
+  }
+
+  if(IsVoid(aType)) {
+    AddVoidArg(i,result,currPos,aType);
+  }
+
+  if(IsClass(aType)) {
+    AddClassArg(i,aType,Id,result,currPos);
+  }
+
+  if(IsUnknown(aType)) {
+    return;
+  }
+
+  if(!IsClass(aType)) {
+    if(IsPtr(aType)) {
+      add_to_sig(result," *",currPos);
+    }
+#if defined(IDL_I_HH) || defined(IDL_I_CC)
+    if(IsString(aType) && !IsIn(aType) && !IsConst(aType) && !IsReturnArg(i)) {
+       add_to_sig(result,"*&",currPos);
+    } else {
+      if(IsString(aType) || (IsReturnArg(i) && IsVoidPtr(aType))) {
+       add_to_sig(result," *",currPos);
+      }
+    }
+#endif
+  }
+
+  if(!IsReturnArg(i)) {
+    sprintf(buf,"temp%i",i);
+    add_to_sig(result,buf,currPos);
+  }
+  
+  return;
+}
+
+void read_class_functions(const char* name, const char* classname, FILE* fp)
+{
+  int len=0;
+  int curlen=0;
+  int i;
+  int j;
+  int flen=0;
+  int num=0;
+  int ret_str=0;
+  FILE *fin;
+  char buf[bs];
+  char buf1[bs];
+  char fname[bs];
+  static char sig[bs];
+  static int slen=8;
+#if ! defined(IDL_I_CC)
+  static int clen=15;
+#else
+  static int clen=7;
+#endif
+
+#if defined(IDL_I_HH)
+  sprintf(buf,"PARAVIS_Gen_%s_i.hh",name);
+#elif defined(IDL_I_CC)
+  sprintf(buf,"PARAVIS_Gen_%s_i.cc",name);
+#else
+  sprintf(buf,"PARAVIS_Gen_%s.idl",name);
+#endif
+  if (!(fin = fopen(buf,"r"))) {
+    fprintf(stderr,"Error opening input file %s\n",buf);
+    exit(1);
+  }
+  while (fgets(sig,bs-1,fin) != 0) {
+#if defined(IDL_I_CC)
+    if(strncmp("#include \"PARAVIS_Gen_vtk",sig,25)==0) {
+      fprintf(fp,sig);
+    }
+    if(strncmp("#include <vtk",sig,13)==0) {
+      fprintf(fp,sig);
+    }
+#endif
+
+#if ! defined(IDL_I_CC)
+    if(strncmp("        //C++: ",sig,clen)==0) {
+#else
+    if(strncmp("//C++: ",sig,clen)==0) {
+#endif
+#if defined(IDL_I_CC)
+      while(fgets(buf,bs-1,fin) != 0) {
+       len=strlen(sig);
+       strcpy(sig+len,buf);
+       if(strlen(buf) == 3 && buf[0]=='/' && buf[1]=='/')
+         break;
+      }
+#endif
+      len=strlen(sig);
+      fgets(buf,bs-1,fin);
+      if(strlen(buf) > 1) {
+       ret_str=0;
+#if defined(IDL_I_HH)
+       strcpy(sig+len,buf);
+       readFunctions[numberOfReadFunctions].EndPos=strlen(sig);  
+       sscanf(sig+len,"%s %s %s",buf,buf1,fname);
+       if(fname[0] == '*') {
+         ret_str=1;
+       }
+#elif defined(IDL_I_CC)
+       strcpy(buf1,buf);
+       sscanf(buf1,"%s %s",buf,fname);
+
+       curlen=strlen(sig);
+       sprintf(sig+curlen,"%s ",buf);
+       j=strlen(buf)+1;
+
+       if(fname[0] == '*') {
+         curlen=strlen(sig);
+         sprintf(sig+curlen," *");
+         j+=1;
+       }
+       curlen=strlen(sig);
+       sprintf(sig+curlen,"%s_i::",classname);
+
+       for(i = 0; i < strlen(fname)-1; i++) {
+         ret_str+=1;
+         j+=1;
+         if(fname[i] == ':' && fname[i] == ':') {
+           ret_str+=1;
+           j+=1;
+           break;
+         }
+       }
+       curlen=strlen(sig);
+       sprintf(sig+curlen,"%s", buf1+j);
+
+       curlen=strlen(sig);
+       readFunctions[numberOfReadFunctions].EndPos=curlen;  
+       while (fgets(sig+curlen,bs-1-curlen,fin) != 0) {
+         if(sig[curlen] == '}')
+           break;
+         curlen=strlen(sig);
+       }
+#else
+       strcpy(sig+len,buf);
+       readFunctions[numberOfReadFunctions].EndPos=strlen(sig);  
+       sscanf(sig+len,"%s _%s",buf,fname);
+#endif
+       flen=strlen(fname);
+       if(flen>0) {
+         if(flen>2 && fname[flen-2]=='_') {
+           flen-=2;
+         }
+         readFunctions[numberOfReadFunctions].Name = malloc((flen+1-ret_str)*sizeof(char));
+         strncpy(readFunctions[numberOfReadFunctions].Name,fname+ret_str,flen-ret_str);
+         readFunctions[numberOfReadFunctions].Name[flen-ret_str]='\0';
+         
+#if defined(IDL_I_HH)
+         len+=slen+strlen(buf)+1+strlen(buf1)+2+flen+ret_str-1; //spaces+virtual+space+return+space+space+*+name
+#elif defined(IDL_I_CC)
+         len+=2+strlen(buf)+2+strlen(classname)+2+strlen(readFunctions[numberOfReadFunctions].Name)-1; //return+space+space+name
+         if(fname[0] == '*') {
+           len+=2;
+         }
+         if(fname[flen-2]=='_') {
+           len+=2;
+         }
+#else
+         len+=slen+strlen(buf)+2+flen; //spaces+return+space+_+name
+#endif
+         readFunctions[numberOfReadFunctions].NumPos=len;
+         if(fname[flen]=='_') {
+           readFunctions[numberOfReadFunctions].NumPos=len+2; //+_+num
+         }
+         
+         len=strlen(sig);
+         readFunctions[numberOfReadFunctions].Signature = malloc((len+1)*sizeof(char));
+         strncpy(readFunctions[numberOfReadFunctions].Signature,sig,len);
+         readFunctions[numberOfReadFunctions].Signature[len]='\0';
+
+         numberOfReadFunctions++;
+       }
+      }
+    }
+  }
+  fclose (fin);
+  return;
+}
+
+void get_signature(const char* num, FileInfo *data)
+{
+  static char result[bs];
+  int currPos = 0;
+  int currPos_sig = 0;
+  int argtype;
+  int i, j;
+  static char buf[bs];
+  static char buf1[bs];
+  int ret = 0;
+  int found = 0;
+  int currPos_num = 0;
+
+  add_to_sig(result,"\n",&currPos);
+  if (currentFunction->Signature) {
+#if ! defined(IDL_I_CC)
+    add_to_sig(result,"        ",&currPos);
+#endif
+    add_to_sig(result,"//C++: ",&currPos);
+    add_to_sig(result,currentFunction->Signature,&currPos);
+    add_to_sig(result,"\n",&currPos);
+  }
+
+  if(IsClass(currentFunction->ReturnType) && ret == 0) {
+    found = 0;
+    for(i = 0; strcmp(wrapped_classes[i],"") != 0 && found == 0; i++) {
+      if(strcmp(wrapped_classes[i],currentFunction->ReturnClass) == 0)
+       found = 1;
+    }
+    if(!found)
+      ret = 1;
+  }
+
+  for (j = 0; j < currentFunction->NumberOfArguments; j++) {
+    if(IsFunction(currentFunction->ArgTypes[j]))
+      ret == 1;
+    if(IsClass(currentFunction->ArgTypes[j]) && ret == 0) {
+      found = 0;
+      for(i = 0; strcmp(wrapped_classes[i],"") != 0 && found == 0; i++) {
+       if(strcmp(wrapped_classes[i],currentFunction->ArgClasses[j]) == 0)
+         found = 1;
+      }
+      if(!found)
+       ret = 1;
+    }
+  }
+
+  if (IsArray(currentFunction->ReturnType) && !IsClass(currentFunction->ReturnType) && !IsString(currentFunction->ReturnType) && currentFunction->HintSize == 0) {
+    ret = 1;
+  }
+
+  if(ret) {
+    add_to_sig(result,"//\n",&currPos);
+    currentFunction->Signature = realloc(currentFunction->Signature,
+                                        (size_t)(currPos+1));
+    strcpy(currentFunction->Signature,result);
+    
+    return;
+  }
+
+#if defined(IDL_I_CC)
+    add_to_sig(result,"struct CreateEventName(",&currPos);
+    add_to_sig(result,currentFunction->Name,&currPos);
+    if( strlen(num)!=0 ) {
+      add_to_sig(result,num,&currPos);
+    }
+    add_to_sig(result,")",&currPos);
+    add_to_sig(result,": public SALOME_Event\n",&currPos);
+    add_to_sig(result,"{\n",&currPos);
+    if(!IsVoid(currentFunction->ReturnType)) {
+      output_typedef(result,&currPos,MAX_ARGS,currentFunction->ReturnType,
+                    currentFunction->ReturnClass);
+      add_to_sig(result," TResult;\n",&currPos);
+      add_to_sig(result,"  TResult myResult;\n",&currPos);
+    }
+    
+    output_typedef(result, &currPos, 0, 0x309,
+                  data->ClassName);
+    add_to_sig(result," TObj;\n",&currPos);
+    add_to_sig(result,"  TObj myObj;\n",&currPos);
+    
+    for (i = 0; i < currentFunction->NumberOfArguments; i++) {
+      output_typedef(result, &currPos, i, currentFunction->ArgTypes[i],
+                    currentFunction->ArgClasses[i]);
+      sprintf(buf," TParam%d;\n",i);
+      add_to_sig(result,buf,&currPos);
+      sprintf(buf,"  TParam%d myParam%d;\n",i,i);
+      add_to_sig(result,buf,&currPos);
+    }
+    
+    add_to_sig(result,"\n",&currPos);  
+    add_to_sig(result,"  CreateEventName(",&currPos);  
+    add_to_sig(result,currentFunction->Name,&currPos);
+    if( strlen(num)!=0 ) {
+      add_to_sig(result,num,&currPos);
+    }
+    add_to_sig(result,")",&currPos);
+    add_to_sig(result,"(TObj theObj",&currPos);  
+    for (i = 0; i < currentFunction->NumberOfArguments; i++) {
+      sprintf(buf,", TParam%d theParam%d",i,i);
+      add_to_sig(result,buf,&currPos);
+    }
+    add_to_sig(result,"):\n",&currPos);  
+    add_to_sig(result,"  myObj(theObj)",&currPos);  
+    for (i = 0; i < currentFunction->NumberOfArguments; i++) {
+      sprintf(buf,", myParam%d(theParam%d)",i,i);
+      add_to_sig(result,buf,&currPos);
+    }
+    add_to_sig(result,"\n",&currPos);  
+    add_to_sig(result,"  { }\n",&currPos);  
+    add_to_sig(result,"\n",&currPos);  
+    add_to_sig(result,"  virtual void Execute()\n",&currPos);  
+    add_to_sig(result,"  {\n",&currPos);  
+    add_to_sig(result,"    ",&currPos);  
+    if(!IsVoid(currentFunction->ReturnType)/* && !IsString(currentFunction->ReturnType)*/) {
+      add_to_sig(result,"myResult = ",&currPos);  
+    }
+    //if(IsString(currentFunction->ReturnType)) {
+    //add_to_sig(result,"const char* ret = ",&currPos);  
+    //}
+    add_to_sig(result,"myObj->",&currPos);  
+    add_to_sig(result,currentFunction->Name,&currPos);  
+    add_to_sig(result,"(",&currPos);  
+    for (i = 0; i < currentFunction->NumberOfArguments; i++) {
+      if(i!=0)
+       add_to_sig(result,", ",&currPos);  
+      if(IsClass(currentFunction->ArgTypes[i]) && IsPtr(currentFunction->ArgTypes[i])) {
+       add_to_sig(result,"*",&currPos);  
+      }
+      sprintf(buf,"myParam%d",i);
+      add_to_sig(result,buf,&currPos);
+    }
+    add_to_sig(result,");\n",&currPos);  
+    //if(IsString(currentFunction->ReturnType)) {
+    //add_to_sig(result,"    myResult = (ret==NULL)?NULL:CORBA::string_dup(\"\");\n",&currPos);  
+    //}
+    add_to_sig(result,"  }\n",&currPos);  
+    
+    add_to_sig(result,"};\n",&currPos);  
+    add_to_sig(result,"//\n",&currPos);  
+#endif
+  currPos_sig=currPos;
+
+#if ! defined(IDL_I_CC)
+  add_to_sig(result,"        ",&currPos);
+#endif
+
+  output_temp(result,&currPos,MAX_ARGS,currentFunction->ReturnType,
+             currentFunction->ReturnClass,0);
+
+#if defined(IDL_I_CC)
+  add_to_sig(result,data->ClassName,&currPos);
+  add_to_sig(result,"_i::",&currPos);
+#endif
+#if ! defined(IDL_I_HH) && ! defined(IDL_I_CC)
+  add_to_sig(result,"_",&currPos);
+#endif
+  add_to_sig(result,currentFunction->Name,&currPos);
+
+  if( strlen(num)!=0 ) {
+    add_to_sig(result,num,&currPos);
+  }
+  currPos_num=currPos;
+  add_to_sig(result," ",&currPos);
+
+  /* print the arg list */
+  add_to_sig(result,"(",&currPos);
+
+  for (i = 0; i < currentFunction->NumberOfArguments; i++) {
+    if( i != 0 ) {
+      add_to_sig(result,", ",&currPos);          
+    }
+    output_temp(result, &currPos, i, currentFunction->ArgTypes[i],
+               currentFunction->ArgClasses[i],
+               currentFunction->ArgCounts[i]);
+  }
+
+  add_to_sig(result,")",&currPos);
+#if defined(IDL_I_CC)
+  add_to_sig(result," {\n",&currPos);
+  add_to_sig(result,"  try {\n",&currPos);
+  for (i = 0; i < currentFunction->NumberOfArguments; i++) {
+    if(IsClass(currentFunction->ArgTypes[i])) {
+      sprintf(buf,"    PARAVIS_Base_i* i_temp%d = GET_SERVANT(temp%d);\n",i,i);
+      add_to_sig(result,buf,&currPos);
+    }
+      
+    if(
+       IsArray(currentFunction->ArgTypes[i])
+       && !IsString(currentFunction->ArgTypes[i])
+       && !IsClass(currentFunction->ArgTypes[i])
+       && !IsVoid(currentFunction->ArgTypes[i])
+       ) {
+      sprintf(buf,"    CORBA::ULong j_temp%d;\n",i);
+      add_to_sig(result,buf,&currPos);
+      sprintf(buf,"    CORBA::ULong l_temp%d = temp%d.length();\n",i,i);
+      add_to_sig(result,buf,&currPos);
+      add_to_sig(result,"    ",&currPos);            
+      
+      if(IsFloat(currentFunction->ArgTypes[i]))
+       add_to_sig(result,"float",&currPos);
+      
+      if(IsDouble(currentFunction->ArgTypes[i]))
+       add_to_sig(result,"double",&currPos);
+      
+      if(IsvtkIdType(currentFunction->ArgTypes[i])) {
+       add_to_sig(result,"vtkIdType",&currPos);
+      } else {
+         if(IsShort(currentFunction->ArgTypes[i])) {
+           add_to_sig(result,"int",&currPos);
+         }
+      }
+      
+      if(IsLong(currentFunction->ArgTypes[i]))
+       add_to_sig(result,"long",&currPos);
+      
+      sprintf(buf,"* a_temp%d = new ",i);
+      add_to_sig(result,buf,&currPos);
+
+      if(IsFloat(currentFunction->ArgTypes[i]))
+       add_to_sig(result,"float",&currPos);
+      
+      if(IsDouble(currentFunction->ArgTypes[i]))
+       add_to_sig(result,"double",&currPos);
+      
+      if(IsvtkIdType(currentFunction->ArgTypes[i])) {
+       add_to_sig(result,"vtkIdType",&currPos);
+      } else {
+       if(IsShort(currentFunction->ArgTypes[i])) {
+         add_to_sig(result,"int",&currPos);
+       }
+      }
+
+      if(IsLong(currentFunction->ArgTypes[i]))
+       add_to_sig(result,"long",&currPos);
+      
+      sprintf(buf,"[l_temp%d];\n",i);
+      add_to_sig(result,buf,&currPos);
+      
+      sprintf(buf,"    for(j_temp%d=0;j_temp%d<l_temp%d;j_temp%d++) {\n",i,i,i,i);
+      add_to_sig(result,buf,&currPos);
+      
+      sprintf(buf,"      a_temp%d[j_temp%d]=temp%d[j_temp%d];\n",i,i,i,i);
+      add_to_sig(result,buf,&currPos);
+      
+      add_to_sig(result,"    }\n",&currPos);
+    }
+
+    if(IsString(currentFunction->ArgTypes[i])) {
+      sprintf(buf,"    char *c_temp%d = CORBA::string_dup(temp%d);\n",i,i);
+      add_to_sig(result,buf,&currPos);
+    }
+
+    if(IsVoid(currentFunction->ArgTypes[i])) {
+      sprintf(buf,"    long v_temp%d;\n",i);
+      add_to_sig(result,buf,&currPos);
+      
+      sprintf(buf,"    temp%d.operator>>=(v_temp%d);\n",i,i);
+      add_to_sig(result,buf,&currPos);
+    }
+  }  
+  add_to_sig(result,"    ",&currPos);
+
+  if(IsArray(currentFunction->ReturnType) && !IsClass(currentFunction->ReturnType) && !IsString(currentFunction->ReturnType)) {
+    add_to_sig(result,"CORBA::ULong i_ret;\n",&currPos); 
+    add_to_sig(result,"    PARAVIS::",&currPos); 
+    AddTypeArray(currentFunction->ReturnType,result,&currPos);
+    add_to_sig(result,"_var s_ret = new ",&currPos);
+    AddTypeArray(currentFunction->ReturnType,result,&currPos);
+    add_to_sig(result,"();\n",&currPos);
+    sprintf(buf,"    s_ret->length(%d);\n",currentFunction->HintSize);
+    add_to_sig(result,buf,&currPos);
+    add_to_sig(result,"    ",&currPos); 
+  }
+  
+  if(IsFloat(currentFunction->ReturnType)) {
+    if(IsArray(currentFunction->ReturnType)) {
+      add_to_sig(result,"float* a_ret = ",&currPos);
+    } else {
+      add_to_sig(result,"CORBA::Float ret = ",&currPos);
+    }
+  }
+  
+  if(IsDouble(currentFunction->ReturnType)) {
+    if(IsArray(currentFunction->ReturnType)) {
+      add_to_sig(result,"double* a_ret = ",&currPos);
+    } else {
+      add_to_sig(result,"CORBA::Double ret = ",&currPos);
+    }
+  }
+  
+  if(IsShort(currentFunction->ReturnType)) {
+    if(IsArray(currentFunction->ReturnType)) {
+      if(IsvtkIdType(currentFunction->ReturnType)) {
+       add_to_sig(result,"vtkIdType",&currPos);
+      } else {
+       add_to_sig(result,"int",&currPos);
+      }
+      add_to_sig(result,"* a_ret = ",&currPos);
+    } else {
+      add_to_sig(result,"CORBA::Short ret = ",&currPos);
+    }
+  }
+  
+  if(IsLong(currentFunction->ReturnType)) {
+    if(IsArray(currentFunction->ReturnType)) {
+      add_to_sig(result,"long* a_ret = ",&currPos);
+    } else {
+      add_to_sig(result,"CORBA::Long ret = ",&currPos);
+    }
+  }
+  
+  if(IsChar(currentFunction->ReturnType)) {
+    if(IsString(currentFunction->ReturnType)) {
+      add_to_sig(result,"char * ret = CORBA::string_dup(\"\");\n",&currPos);
+      add_to_sig(result,"    const char * cret = ",&currPos);
+    } else {
+      add_to_sig(result,"CORBA::Char ret = ",&currPos);            
+    }
+  }
+
+  if(IsBoolean(currentFunction->ReturnType)) {
+    add_to_sig(result,"CORBA::Boolean ret = ",&currPos);
+  }
+  
+  if(IsVoidPtr(currentFunction->ReturnType)) {
+    add_to_sig(result,"void * v_ret = ",&currPos);
+  }
+  
+  if(IsClass(currentFunction->ReturnType)) {
+    add_to_sig(result,"::",&currPos);
+    add_to_sig(result,currentFunction->ReturnClass,&currPos);
+    add_to_sig(result,"* a",&currPos);
+    add_to_sig(result,currentFunction->ReturnClass,&currPos);
+    add_to_sig(result," = ",&currPos);
+  }
+  if(IsVoid(currentFunction->ReturnType)) {
+    add_to_sig(result,"if(getVTKObject() != NULL) ProcessVoidEvent",&currPos);
+  } else {
+    add_to_sig(result,"(getVTKObject() != NULL) ? ProcessEvent",&currPos);
+  }
+  add_to_sig(result,"(\n",&currPos);
+  add_to_sig(result,"      new CreateEventName(",&currPos);
+  add_to_sig(result,currentFunction->Name,&currPos);
+  if( strlen(num)!=0 ) {
+    add_to_sig(result,num,&currPos);
+  }
+  add_to_sig(result,")",&currPos);
+  
+  add_to_sig(result,"((::",&currPos);
+  add_to_sig(result,data->ClassName,&currPos);       
+  add_to_sig(result,"*)",&currPos);
+  add_to_sig(result,"getVTKObject()\n",&currPos);
+  
+  for (i = 0; i < currentFunction->NumberOfArguments; i++) {
+    add_to_sig(result,"      , ",&currPos);
+    
+    //if(IsClass(currentFunction->ArgTypes[i]) && IsPtr(currentFunction->ArgTypes[i])) {
+    //add_to_sig(result,"*(",&currPos);
+    //}
+    
+    if(IsClass(currentFunction->ArgTypes[i])) {
+      sprintf(buf,"(i_temp%d != NULL)?dynamic_cast< ::%s*>(i_temp%d->getVTKObject()):NULL",i,currentFunction->ArgClasses[i],i);
+    } else {
+      if(
+        IsArray(currentFunction->ArgTypes[i])
+        && !IsString(currentFunction->ArgTypes[i])
+        && !IsVoid(currentFunction->ArgTypes[i])
+        ) {
+       sprintf(buf,"a_temp%d",i);
+      } else {
+       if(IsVoidPtr(currentFunction->ArgTypes[i])) {
+         sprintf(buf,"(void*)v_temp%d",i);
+       } else {
+         if(IsString(currentFunction->ArgTypes[i])) {
+           sprintf(buf,"c_temp%d",i);
+         } else {
+           sprintf(buf,"temp%d",i);
+         }
+       }
+      }
+    }
+      
+    add_to_sig(result,buf,&currPos);
+    //if(IsClass(currentFunction->ArgTypes[i]) && IsPtr(currentFunction->ArgTypes[i])) {
+    //add_to_sig(result,")",&currPos);
+    //}
+    add_to_sig(result,"\n",&currPos);
+  }
+
+  add_to_sig(result,"      )\n",&currPos);           
+  add_to_sig(result,"    )",&currPos);
+  if(!IsVoid(currentFunction->ReturnType)) {
+    add_to_sig(result,":",&currPos);
+    if(IsClass(currentFunction->ReturnType) || IsString(currentFunction->ReturnType) || IsPtr(currentFunction->ReturnType) || IsArray(currentFunction->ReturnType))
+      add_to_sig(result,"NULL",&currPos);
+    else
+      add_to_sig(result,"0",&currPos);
+  }
+  add_to_sig(result,";\n",&currPos);
+  if(IsString(currentFunction->ReturnType)) {
+    add_to_sig(result,"    if(cret!=NULL) ret=CORBA::string_dup(cret);\n",&currPos);
+  }
+  
+  if(IsClass(currentFunction->ReturnType)) {
+    add_to_sig(result,"    if(a",&currPos);
+    add_to_sig(result,currentFunction->ReturnClass,&currPos);        
+    add_to_sig(result," == NULL) {\n",&currPos);
+    add_to_sig(result,"      return PARAVIS::",&currPos);            
+    add_to_sig(result,currentFunction->ReturnClass,&currPos);        
+    add_to_sig(result,"::_nil();\n",&currPos);       
+    add_to_sig(result,"    }\n",&currPos);           
+    add_to_sig(result,"    ",&currPos);              
+    add_to_sig(result,"PARAVIS_Base_i* aPtr = ::CreateInstance(a",&currPos);         
+    add_to_sig(result,currentFunction->ReturnClass,&currPos);        
+    add_to_sig(result,", a",&currPos);       
+    add_to_sig(result,currentFunction->ReturnClass,&currPos);        
+    add_to_sig(result,"->GetClassName());\n",&currPos);
+    add_to_sig(result,"    aPtr->Init(a",&currPos);          
+    add_to_sig(result,currentFunction->ReturnClass,&currPos);        
+    add_to_sig(result,");\n",&currPos);              
+  }
+    
+  for (i = 0; i < currentFunction->NumberOfArguments; i++) {
+    if(
+       IsArray(currentFunction->ArgTypes[i])
+       && !IsVoid(currentFunction->ArgTypes[i])
+       && !IsString(currentFunction->ArgTypes[i])
+       && !IsClass(currentFunction->ArgTypes[i])
+       ) {
+      if (!IsIn(currentFunction->ArgTypes[i])) {
+       sprintf(buf,"    for(j_temp%d=0;j_temp%d<l_temp%d;j_temp%d++) {\n",i,i,i,i);
+       add_to_sig(result,buf,&currPos);
+       
+       sprintf(buf,"      temp%d[j_temp%d]=a_temp%d[j_temp%d];\n",i,i,i,i);
+       add_to_sig(result,buf,&currPos);
+       
+       add_to_sig(result,"    }\n",&currPos);
+      }
+      sprintf(buf,"    delete [] a_temp%d;\n",i);
+      add_to_sig(result,buf,&currPos);
+    }
+  }
+
+  if (IsVoid(currentFunction->ReturnType) && !IsVoidPtr(currentFunction->ReturnType)) {
+    add_to_sig(result,"    return;\n",&currPos); 
+  } else {
+    if(IsClass(currentFunction->ReturnType)) {
+      add_to_sig(result,"    return aPtr->_this();\n",&currPos);
+    } else {
+      if(IsVoid(currentFunction->ReturnType)) {
+       add_to_sig(result,"    CORBA::Any* ret = new CORBA::Any;\n",&currPos);
+       add_to_sig(result,"    (*ret) <<= v_ret;\n",&currPos);
+       add_to_sig(result,"    return ret;\n",&currPos); 
+      } else {
+       if(IsArray(currentFunction->ReturnType) && !IsString(currentFunction->ReturnType)) {
+         sprintf(buf,"    for(i_ret=0; i_ret<%d; i_ret++) {\n",currentFunction->HintSize);
+         add_to_sig(result,buf,&currPos); 
+         add_to_sig(result,"      s_ret[i_ret]=a_ret[i_ret];\n",&currPos); 
+         add_to_sig(result,"    }\n",&currPos); 
+         add_to_sig(result,"    return s_ret._retn();\n",&currPos); 
+       } else {
+         add_to_sig(result,"    return ret;\n",&currPos); 
+       }
+      }
+    }
+  }
+
+  add_to_sig(result,"  } catch(...) {\n",&currPos);
+  add_to_sig(result,"    MESSAGE(\"",&currPos);
+  //add_to_sig(result,data->ClassName,&currPos);             
+  //add_to_sig(result,"::",&currPos);
+  add_to_sig(result,currentFunction->Name,&currPos);         
+  add_to_sig(result," - Unknown exception was occured!!!\");\n",&currPos);
+
+  if (IsVoid(currentFunction->ReturnType)&& !IsVoidPtr(currentFunction->ReturnType)) {
+    add_to_sig(result,"    return;\n",&currPos);
+  } else{
+    if(IsString(currentFunction->ReturnType)) {
+      add_to_sig(result,"    return CORBA::string_dup(\"\");\n",&currPos);
+    } else {
+      if(IsClass(currentFunction->ReturnType)) {
+       add_to_sig(result,"    return PARAVIS::",&currPos);
+       add_to_sig(result,currentFunction->ReturnClass,&currPos);
+       add_to_sig(result,"::_nil();\n",&currPos);
+      } else {
+       if(IsArray(currentFunction->ReturnType) && !IsVoid(currentFunction->ReturnType)) {
+         add_to_sig(result,"    PARAVIS::",&currPos);
+         AddTypeArray(currentFunction->ReturnType,result,&currPos);
+         add_to_sig(result,"_var s_ret = new ",&currPos);
+         AddTypeArray(currentFunction->ReturnType,result,&currPos);
+         add_to_sig(result,"();\n",&currPos);
+         sprintf(buf,"    s_ret->length(%d);\n",currentFunction->HintSize);
+         add_to_sig(result,buf,&currPos);
+         add_to_sig(result,"    return s_ret._retn();\n",&currPos);
+       } else {
+         add_to_sig(result,"    return 0;\n",&currPos);
+       }
+      }
+    }
+  }
+
+  add_to_sig(result,"  }\n",&currPos);
+  add_to_sig(result,"}\n",&currPos);
+#else
+  add_to_sig(result,";\n",&currPos);
+#endif
+
+  if(ret)
+    {
+      result[currPos_sig]='\0';
+      currentFunction->Signature = realloc(currentFunction->Signature,
+                                          (size_t)(currPos_sig+1));
+      strcpy(currentFunction->Signature,result);
+
+      return;
+    }
+
+  //if(strcmp(currentFunction->Name,"NewInstance") == 0) {
+  //currentFunction->Signature[0]='\0';
+  //return;
+  //}
+
+  for(i = 0; i < numberOfReadFunctions; i++) {
+    if(strcmp(readFunctions[i].Name,currentFunction->Name) == 0) {
+      j=readFunctions[i].EndPos-readFunctions[i].NumPos;
+      strncpy(buf,result+currPos_num,j);
+      strncpy(buf1,readFunctions[i].Signature+readFunctions[i].NumPos,j);
+      buf[j]=0;
+      buf1[j]=0;
+      if(strcmp(buf,buf1) == 0) {
+       currentFunction->Signature[0]='\0';
+       return;
+      }
+    }
+  }
+
+  currentFunction->Signature = realloc(currentFunction->Signature,
+                                       (size_t)(currPos+1));
+  strcpy(currentFunction->Signature,result);
+}
+
+void outputFunction2(FILE *fp, FileInfo *data)
+{
+  int i, j, k, is_static, is_vtkobject, fnum, occ, backnum, goto_used;
+  int all_legacy;
+  FunctionInfo *theFunc;
+  FunctionInfo *backFunc;
+  char *theName;
+  int theType;
+  char *backName;
+  int backType;
+  char static num[8];
+  //int isSMObject = 0;
+  int found = 0;
+
+#if defined(IDL_I_HH)
+  fprintf(fp,"#include \"SALOMEconfig.h\"\n");
+  fprintf(fp,"#include CORBA_SERVER_HEADER(PARAVIS_Gen_%s)\n",data->ClassName);
+  fprintf(fp,"\n");
+  fprintf(fp,"#include \"SALOME_GenericObj_i.hh\"\n");
+  fprintf(fp,"#include \"PARAVIS_Gen_i.hh\"\n");
+  fprintf(fp,"#include \"PARAVIS_Gen_Types.hh\"\n");
+  fprintf(fp,"#include \"vtkSmartPointer.h\"\n");
+  fprintf(fp,"#include \"SALOME_Event.h\"\n");
+
+  for(i=0;i<data->NumberOfSuperClasses;i++)
+  {
+    fprintf(fp,"#include \"PARAVIS_Gen_%s_i.hh\"\n",data->SuperClasses[i]);
+  }
+
+  fprintf(fp,"\nclass %s;\n",data->ClassName);
+  fprintf(fp,"\nnamespace PARAVIS\n{\n\n");
+#elif defined(IDL_I_CC)
+  fprintf(fp,"#include \"SALOME_GenericObj_i.hh\"\n");
+  fprintf(fp,"#include \"PARAVIS_Gen_%s_i.hh\"\n",data->ClassName);
+  fprintf(fp,"#include \"PV_Tools.h\"\n");
+  fprintf(fp,"#include \"SALOME_Event.h\"\n");
+  fprintf(fp,"#include <%s.h>\n",data->ClassName);
+#else
+  fprintf(fp,"#include \"PARAVIS_Gen.idl\"\n");
+  fprintf(fp,"#include \"PARAVIS_Gen_Types.idl\"\n");
+
+  for(i=0;i<data->NumberOfSuperClasses;i++)
+  {
+    fprintf(fp,"#include \"PARAVIS_Gen_%s.idl\"\n",data->SuperClasses[i]);
+  }
+
+  fprintf(fp,"\nmodule PARAVIS\n{\n\n");
+#endif
+
+  is_vtkobject = ((strcmp(data->ClassName,"vtkObjectBase") == 0) || 
+                  (data->NumberOfSuperClasses != 0));
+
+  for(i = 0; i < data->NumberOfSuperClasses; i++) {
+    read_class_functions(data->SuperClasses[i],data->ClassName,fp);
+  }
+
+  /* create a idl signature for each method */
+  for (fnum = 0; fnum < numberOfWrappedFunctions; fnum++)
+    {
+
+    theFunc = wrappedFunctions[fnum];
+    currentFunction = theFunc;
+
+    /* names of idl methods should be unique */
+    num[0]='\0';
+    j=-1;
+    for (i = 0; i < numberOfReadFunctions; i++) {
+      if(strcmp(currentFunction->Name,readFunctions[i].Name) == 0)
+       j++;
+    }
+
+    for (i = 0; i < fnum; i++)
+      {
+       if( strcmp(currentFunction->Name,wrappedFunctions[i]->Name) ==  0 )
+         j++;
+      }
+
+    if(j<0) {
+      for (i = fnum+1; i < numberOfWrappedFunctions; i++) {
+       if( strcmp(currentFunction->Name,wrappedFunctions[i]->Name) ==  0 ) {
+         j=0;
+         break;
+       }
+      }
+    } else {
+      j++;
+    }
+
+    if(j>=0)
+      {
+       sprintf(num,"_%d",j);
+      }
+
+    get_signature(num,data);
+    }
+
+  /* create external type declarations for all object
+     return types */
+  for (fnum = 0; fnum < numberOfWrappedFunctions; fnum++)
+    {
+    theFunc = wrappedFunctions[fnum];
+    currentFunction = theFunc;
+    theName = NULL;
+    theType = 0;
+
+    for (i = theFunc->NumberOfArguments; i >= 0; i--)
+      {
+       if (i==0)/* return type */
+         {
+           theType = theFunc->ReturnType;
+           theName = theFunc->ReturnClass;
+         }
+       else /* arg type */
+         {
+           theType = theFunc->ArgTypes[i-1];
+           theName = theFunc->ArgClasses[i-1];
+         }
+       /* check for object types */
+       if ((theType % 0x1000 == 0x309)||
+           (theType % 0x1000 == 0x109))
+         {
+           /* check that we haven't done this type (no duplicate declarations) */
+           for (backnum = fnum; backnum >= 0; backnum--) 
+             {
+               backFunc = wrappedFunctions[backnum];
+               backName = NULL;
+               backType = 0;
+               if (backnum == fnum)
+                 k = i+1;
+               else
+                 k = 0;
+               for (j = backFunc->NumberOfArguments; j >= k; j--)
+                 {
+                   if (j==0) /* return type */
+                     {
+                       backType = backFunc->ReturnType;
+                       backName = backFunc->ReturnClass;
+                     }
+                   else /* arg type */
+                     {
+                       backType = backFunc->ArgTypes[j-1];
+                       backName = backFunc->ArgClasses[j-1];
+                     }
+                   if (((backType % 0x1000 == 0x309)||
+                        (backType % 0x1000 == 0x109)))
+                     {
+                       if(strcmp(theName,backName) == 0)
+                         {
+                           break;
+                         }
+                     }
+                 }
+               if (j >= k)
+                 {
+                   break;
+                 }
+             }
+           if (backnum < 0 && strcmp(data->ClassName,theName) != 0)
+             {
+               found = 0;
+               for(j = 0; strcmp(wrapped_classes[j],"") != 0 && found == 0; j++)
+                 {
+                   if(strcmp(wrapped_classes[j],theName) == 0)
+                     found = 1;
+                 }
+               if(found)
+                 {
+#if defined(IDL_I_HH)
+                   fprintf(fp,"    class %s_i;\n",theName);
+#elif defined(IDL_I_CC)
+                   fprintf(fp,"#include \"PARAVIS_Gen_%s_i.hh\"\n",theName);
+                   fprintf(fp,"#include <%s.h>\n",theName);
+#else
+                   //fprintf(fp,"#include \"PARAVIS_Gen_%s.idl\"\n",theName);
+                   fprintf(fp,"    interface %s;\n",theName);
+#endif
+                 }
+             }
+         }
+      }
+    }
+
+  //fprintf(fp,"\nmodule PARAVIS\n{\n");
+#if defined(IDL_I_HH)
+  fprintf(fp,"\n    class %s_i : public virtual POA_PARAVIS::%s, public virtual PARAVIS::PARAVIS_Base_i",data->ClassName,data->ClassName);
+  //for(i = 0; i < data->NumberOfSuperClasses; i++) {
+  //  fprintf(fp,", public virtual %s_i",data->SuperClasses[i]);
+  //}
+  //fprintf(fp,", public virtual SALOME::GenericObj_i");
+  fprintf(fp," {");
+  fprintf(fp,"\n    public:\n");
+  fprintf(fp,"\n        %s_i();\n",data->ClassName);
+#elif defined(IDL_I_CC)
+  fprintf(fp,"extern PARAVIS::PARAVIS_Base_i* CreateInstance(::vtkObjectBase* Inst, const QString&);\n");
+  fprintf(fp,"\nnamespace PARAVIS\n{\n");
+  fprintf(fp,"typedef %s_i current_inderface;\n",data->ClassName);
+  fprintf(fp,"#define CreateEventName(Function) Event%s ##Function\n",data->ClassName);
+  fprintf(fp,"%s_i::%s_i() {\n",data->ClassName,data->ClassName);
+  fprintf(fp,"    Init(::%s::New());\n",data->ClassName);
+  fprintf(fp,"}\n");
+  fprintf(fp,"\n");
+#else
+  fprintf(fp,"\n    interface %s : PARAVIS_Base",data->ClassName);
+  fprintf(fp,"\n    {\n");
+#endif
+
+  for(i = 0; i < numberOfReadFunctions; i++) {
+    fprintf(fp, "%s\n", readFunctions[i].Signature);
+  }
+
+  for (fnum = 0; fnum < numberOfWrappedFunctions; fnum++) {
+    fprintf(fp,"%s\n",wrappedFunctions[fnum]->Signature);
+  }
+
+#if defined(IDL_I_HH)
+  fprintf(fp,"    };\n");
+  fprintf(fp,"}\n");
+#elif defined(IDL_I_CC)
+  fprintf(fp,"};\n");
+#else
+  fprintf(fp,"    };\n");
+  fprintf(fp,"};\n");
+#endif
+
+  return;
+}
+
+void outputFunction(FILE *fp, FileInfo *data)
+{
+  int i;
+  int args_ok = 1;
+  fp = fp;
+  /* some functions will not get wrapped no matter what else,
+     and some really common functions will appear only in vtkObjectPython */
+  if (currentFunction->IsOperator || 
+      currentFunction->ArrayFailure ||
+      !currentFunction->IsPublic ||
+      !currentFunction->Name)
+    {
+      return;
+    }
+  
+  /* check to see if we can handle the args */
+  for (i = 0; i < currentFunction->NumberOfArguments; i++)
+    {
+    if (currentFunction->ArgTypes[i] % 0x1000 == 9) args_ok = 0;
+    if ((currentFunction->ArgTypes[i] % 0x10) == 8) args_ok = 0;
+    if (((currentFunction->ArgTypes[i] % 0x1000)/0x100 != 0x3)&&
+        (currentFunction->ArgTypes[i] % 0x1000 != 0x109)&&
+        ((currentFunction->ArgTypes[i] % 0x1000)/0x100)) args_ok = 0;
+    if (currentFunction->ArgTypes[i] % 0x1000 == 0x313) args_ok = 0;
+    if (currentFunction->ArgTypes[i] % 0x1000 == 0x314) args_ok = 0;
+    if (currentFunction->ArgTypes[i] % 0x1000 == 0x31A) args_ok = 0;
+    if (currentFunction->ArgTypes[i] % 0x1000 == 0x31B) args_ok = 0;
+    if (currentFunction->ArgTypes[i] % 0x1000 == 0x31C) args_ok = 0;
+    if (currentFunction->ArgTypes[i] % 0x1000 == 0x315) args_ok = 0;
+    if (currentFunction->ArgTypes[i] % 0x1000 == 0x316) args_ok = 0;
+    }
+  if ((currentFunction->ReturnType % 0x10) == 0x8) args_ok = 0;
+  if (currentFunction->ReturnType % 0x1000 == 0x9) args_ok = 0;
+  if (((currentFunction->ReturnType % 0x1000)/0x100 != 0x3)&&
+      (currentFunction->ReturnType % 0x1000 != 0x109)&&
+      ((currentFunction->ReturnType % 0x1000)/0x100)) args_ok = 0;
+
+
+  /* eliminate unsigned char * and unsigned short * */
+  if (currentFunction->ReturnType % 0x1000 == 0x313) args_ok = 0;
+  if (currentFunction->ReturnType % 0x1000 == 0x314) args_ok = 0;
+  if (currentFunction->ReturnType % 0x1000 == 0x31A) args_ok = 0;
+  if (currentFunction->ReturnType % 0x1000 == 0x31B) args_ok = 0;
+  if (currentFunction->ReturnType % 0x1000 == 0x31C) args_ok = 0;
+  if (currentFunction->ReturnType % 0x1000 == 0x315) args_ok = 0;
+  if (currentFunction->ReturnType % 0x1000 == 0x316) args_ok = 0;
+
+  if (currentFunction->NumberOfArguments && 
+      (currentFunction->ArgTypes[0] == 0x5000)
+      &&(currentFunction->NumberOfArguments != 0x1)) args_ok = 0;
+
+  /* make sure we have all the info we need for array arguments in */
+  for (i = 0; i < currentFunction->NumberOfArguments; i++)
+    {
+    if (((currentFunction->ArgTypes[i] % 0x1000)/0x100 == 0x3)&&
+        (currentFunction->ArgCounts[i] <= 0)&&
+        (currentFunction->ArgTypes[i] % 0x1000 != 0x309)&&
+        (currentFunction->ArgTypes[i] % 0x1000 != 0x303)&&
+        (currentFunction->ArgTypes[i] % 0x1000 != 0x302)) args_ok = 0;
+    }
+
+  /* if we need a return type hint make sure we have one */
+  switch (currentFunction->ReturnType % 0x1000)
+    {
+    case 0x301: case 0x307: case 0x30A: case 0x30B: case 0x30C: case 0x30D: case 0x30E:
+    case 0x304: case 0x305: case 0x306:
+      args_ok = currentFunction->HaveHint;
+      break;
+    }
+  
+  /* make sure it isn't a Delete or New function */
+  if (!strcmp("Delete",currentFunction->Name) ||
+      !strcmp("New",currentFunction->Name))
+    {
+    args_ok = 0;
+    }
+  
+  /* check for New() function */
+  if (!strcmp("New",currentFunction->Name) &&
+      currentFunction->NumberOfArguments == 0)
+    {
+    class_has_new = 1;
+    }
+
+  if (currentFunction->IsPublic && args_ok && 
+      strcmp(data->ClassName,currentFunction->Name) &&
+      strcmp(data->ClassName, currentFunction->Name + 1))
+    {
+    wrappedFunctions[numberOfWrappedFunctions] = currentFunction;
+    numberOfWrappedFunctions++;
+    }
+
+  return;
+}
+
+/* print the parsed structures */
+void vtkParseOutput(FILE *fp, FileInfo *data)
+{
+  int i;
+
+#if defined(IDL_I_HH)
+  fprintf(fp, "// idl wrapper interface for %s object implementation\n//\n", data->ClassName);
+#elif defined(IDL_I_CC)
+  fprintf(fp, "// idl wrapper implementation for %s object\n//\n", data->ClassName);
+#else
+  fprintf(fp, "// idl wrapper for %s object\n//\n", data->ClassName);
+#endif
+  for (i = 0;1;i++)
+    {
+      if(strlen(Copyright[i]) != 0)
+       {
+         fprintf(fp,"%s\n",Copyright[i]);
+       }
+      else
+       {
+         break;
+       }
+    }
+  fprintf(fp,"\n");
+#if defined(IDL_I_HH)
+  fprintf(fp,"#ifndef PARAVIS_Gen_%s_i_HeaderFile\n",data->ClassName);
+  fprintf(fp,"#define PARAVIS_Gen_%s_i_HeaderFile\n",data->ClassName);
+  fprintf(fp,"\n");
+#elif defined(IDL_I_CC)
+#else
+  fprintf(fp,"#ifndef __PARAVIS_Gen_%s__\n",data->ClassName);
+  fprintf(fp,"#define __PARAVIS_Gen_%s__\n",data->ClassName);
+  fprintf(fp,"\n");
+#endif
+
+  /* insert function handling code here */
+  for (i = 0; i < data->NumberOfFunctions; i++)
+    {
+      currentFunction = data->Functions + i;
+      outputFunction(fp, data);
+    }
+
+  if (data->NumberOfSuperClasses || !data->IsAbstract)
+    {
+    outputFunction2(fp, data);
+    }
+
+#if defined(IDL_I_HH)
+  fprintf(fp,"\n#endif\n");
+#elif defined(IDL_I_CC)
+#else
+  fprintf(fp,"\n#endif\n");
+#endif
+  return;
+}
index 075f10289a0aa8fa7c82c0101f64e335084a93db..8c0628149c78795f1a15724d040ea96d56fd11c8 100644 (file)
@@ -28,4 +28,7 @@ include $(top_srcdir)/adm_local/unix/make_common_starter.am
 dist_salomeres_DATA = \
        LightApp.xml \
        SalomeApp.xml \
-       pqAppIcon22.png
+       pqAppIcon22.png \
+       pqAppIcon16.png
+
+nodist_salomeres_SCRIPTS = PARAVISCatalog.xml
diff --git a/resources/PARAVISCatalog.xml.in b/resources/PARAVISCatalog.xml.in
new file mode 100644 (file)
index 0000000..bd35b2b
--- /dev/null
@@ -0,0 +1,66 @@
+<?xml version='1.0' encoding='us-ascii' ?>
+<!--
+  Copyright (C) 2007-2008  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.
+
+  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
+
+-->
+<!-- XML component catalog -->
+<begin-catalog>
+    <path-prefix-list></path-prefix-list>
+    <type-list></type-list>
+    <component-list>
+        <component>
+            <component-name>PARAVIS</component-name>
+            <component-username>ParaView</component-username>
+            <component-type>PARAVIS</component-type>
+            <component-author>vsv</component-author>
+            <component-version>@VERSION@</component-version>
+            <component-comment>ParaView module</component-comment>
+            <component-multistudy>1</component-multistudy>
+            <component-impltype>1</component-impltype>
+            <component-icone>pqAppIcon22.png</component-icone>
+            <constraint></constraint>
+            <component-interface-list>
+                <component-interface-name>PARAVIS_Gen</component-interface-name>
+                <component-interface-comment>unknown</component-interface-comment>
+                <component-service-list>
+                    <component-service>
+                        <service-name>ImportFile</service-name>
+                        <service-author>vsv</service-author>
+                        <service-version>INF_VERSION</service-version>
+                        <service-comment>unknown</service-comment>
+                        <service-by-default>0</service-by-default>
+                        <inParameter-list>
+                            <inParameter>
+                                <inParameter-name>theFileName</inParameter-name>
+                                <inParameter-type>string</inParameter-type>
+                                <inParameter-comment>unknown</inParameter-comment>
+                            </inParameter>
+                        </inParameter-list>
+                        <outParameter-list></outParameter-list>
+                        <DataStream-list></DataStream-list>
+                    </component-service>
+                </component-service-list>
+            </component-interface-list>
+        </component>
+    </component-list>
+</begin-catalog>
index 02f36852ecc97a162ff85cbbc74595b54f22a2c6..c44ed9592500a799235a09b9354c355f8ad543ad 100644 (file)
@@ -3,11 +3,19 @@
     <!-- Major module parameters -->
     <parameter name="name" value="ParaViS"/>
     <parameter name="icon" value="pqAppIcon22.png"/>
+    <parameter name="singleton" value="true"/>
+    <!-- Lists all additional popup items separated by ':' -->
+    <parameter name="popupitems" value="importmed"/>
   </section>
   <section name="resources">
     <!-- Module resources -->
     <parameter name="PARAVIS" value="${PARAVIS_ROOT_DIR}/share/salome/resources/paravis"/>
     <!-- ParaView pixmaps -->
-    <parameter name="ParaView" value="${PVSRCHOME}/Qt/Components/Resources/Icons"/>
+    <parameter name="ParaView" value="${PVHOME}/include/paraview-${PVVERSION}/Qt/Components/Resources/Icons"/>
+  </section>
+  <section name="importmed">
+    <parameter name="title" value="Load to ParaView"/>
+    <parameter name="attributelocalid" value="20"/>
+    <parameter name="method" value="onImportFromVisu"/>
   </section>
 </document>
diff --git a/resources/pqAppIcon16.png b/resources/pqAppIcon16.png
new file mode 100644 (file)
index 0000000..38713ca
Binary files /dev/null and b/resources/pqAppIcon16.png differ
diff --git a/src/ENGINE/Makefile.am b/src/ENGINE/Makefile.am
new file mode 100644 (file)
index 0000000..a174425
--- /dev/null
@@ -0,0 +1,41 @@
+#  Copyright (C) 2007-2008  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.
+#
+#  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   : Makefile.in
+#  Author : Vitaly Smetannikov
+#  Module : PARAVIS
+#  $Header: 
+#
+include $(top_srcdir)/adm_local/unix/make_common_starter.am
+
+lib_LTLIBRARIES= libPARAVISEngine.la
+
+salomeinclude_HEADERS= PARAVIS_Engine_i.hh
+
+dist_libPARAVISEngine_la_SOURCES= PARAVIS_Engine_i.cc
+
+libPARAVISEngine_la_CPPFLAGS= \
+       $(KERNEL_CXXFLAGS) $(CORBA_CXXFLAGS) $(CORBA_INCLUDES) \
+       -I$(top_builddir)/salome_adm/unix -I$(top_builddir)/idl 
+
+libPARAVISEngine_la_LDFLAGS= \
+       $(KERNEL_LDFLAGS) -lSalomeIDLKernel -lSalomeNS -lSalomeContainer $(CORBA_LIBS) \
+       $(top_builddir)/idl/libSalomeIDLPARAVIS.la
diff --git a/src/ENGINE/PARAVIS_Engine_i.cc b/src/ENGINE/PARAVIS_Engine_i.cc
new file mode 100644 (file)
index 0000000..ee16c93
--- /dev/null
@@ -0,0 +1,278 @@
+//  Copyright (C) 2007-2008  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.
+//
+//  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
+//
+#include "PARAVIS_Engine_i.hh"
+#include "utilities.h"
+
+#include CORBA_SERVER_HEADER(SALOME_ModuleCatalog)
+
+#include "SALOME_NamingService.hxx"
+#include "Utils_ExceptHandlers.hxx"
+
+using namespace std;
+
+#ifdef _DEBUG_
+static int MYDEBUG = 1;
+#else
+static int MYDEBUG = 0;
+#endif
+
+#ifdef WNT
+#if defined PARAVIS_ENGINE_EXPORTS || defined PARAVISEngine_EXPORTS
+#define PARAVIS_ENGINE_EXPORT __declspec(dllexport)
+#else
+#define PARAVIS_ENGINE_EXPORT __declspec(dllimport)
+#endif
+#else
+#define PARAVIS_ENGINE_EXPORT
+#endif
+
+UNEXPECT_CATCH(SalomeException, SALOME::SALOME_Exception);
+
+extern "C" {
+PARAVIS_ENGINE_EXPORT PortableServer::ObjectId* PARAVISEngine_factory(CORBA::ORB_ptr orb, 
+                                                                      PortableServer::POA_ptr poa, 
+                                                                      PortableServer::ObjectId * contId,
+                                                                      const char *instanceName, 
+                                                                      const char *interfaceName) 
+{
+  MESSAGE("PARAVISEngine_factory : "<<interfaceName);
+  SALOME_NamingService aNamingService(orb);
+  CORBA::Object_ptr anObject = aNamingService.Resolve("/Kernel/Session");
+  SALOME::Session_var aSession = SALOME::Session::_narrow(anObject);
+  if (CORBA::is_nil(aSession))
+    return NULL;
+  
+  PARAVIS::PARAVIS_Gen_i* pPARAVIS_Gen = new PARAVIS::PARAVIS_Gen_i(aSession, 
+                                                                    orb, 
+                                                                    poa, 
+                                                                    contId, 
+                                                                    instanceName, 
+                                                                    interfaceName);
+  return pPARAVIS_Gen->getId() ;
+}
+}
+
+namespace PARAVIS {
+  //===========================================================================
+  PARAVIS_Gen_i::PARAVIS_Gen_i(SALOME::Session_ptr session,
+                               CORBA::ORB_ptr orb,
+                               PortableServer::POA_ptr poa,
+                               PortableServer::ObjectId * contId, 
+                               const char *instanceName, 
+                               const char *interfaceName) :
+    Engines_Component_i(orb, poa, contId, instanceName, interfaceName)
+  {
+    _thisObj = this ;
+    _id = _poa->activate_object(_thisObj);
+#ifndef WIN32
+    Engines::Component_var aComponent = session->GetComponent("libPARAVIS.so");
+#else
+    Engines::Component_var aComponent = session->GetComponent("PARAVIS.dll");
+#endif
+    if (CORBA::is_nil(aComponent)) {
+      MESSAGE("Component PARAVIS is null");
+      return;
+    }
+    myParaVisGen = PARAVIS::PARAVIS_Gen::_narrow(aComponent);
+  } 
+  
+  //===========================================================================
+  PARAVIS_Gen_i::~PARAVIS_Gen_i()
+  {
+    if(MYDEBUG) MESSAGE("PARAVIS_Gen_i::~PARAVIS_Gen_i");
+  }
+
+
+  //===========================================================================
+  char* PARAVIS_Gen_i::GetIOR(){
+    return myParaVisGen->GetIOR();
+  }
+
+  //===========================================================================
+  bool PARAVIS_Gen_i::Load(SALOMEDS::SComponent_ptr theComponent,
+                        const SALOMEDS::TMPFile & theStream,
+                        const char* theURL,
+                        bool isMultiFile)
+  {
+    return myParaVisGen->Load(theComponent,theStream,theURL,isMultiFile);
+  }
+
+  //===========================================================================
+  bool PARAVIS_Gen_i::LoadASCII(SALOMEDS::SComponent_ptr theComponent,
+                             const SALOMEDS::TMPFile & theStream,
+                             const char* theURL,
+                             bool isMultiFile) 
+  {
+    return Load(theComponent, theStream, theURL, isMultiFile);
+  }
+
+
+  //===========================================================================
+  char* PARAVIS_Gen_i::LocalPersistentIDToIOR(SALOMEDS::SObject_ptr theSObject,
+                                           const char* aLocalPersistentID,
+                                           CORBA::Boolean isMultiFile,
+                                           CORBA::Boolean isASCII) 
+  {
+    return myParaVisGen->LocalPersistentIDToIOR(theSObject, aLocalPersistentID, isMultiFile, isASCII);
+  }
+
+  //===========================================================================
+  SALOMEDS::TMPFile* PARAVIS_Gen_i::Save(SALOMEDS::SComponent_ptr theComponent,
+                                     const char* theURL,
+                                     bool isMultiFile)
+  {
+    return myParaVisGen->Save(theComponent,theURL,isMultiFile);
+  }
+
+  //===========================================================================
+  SALOMEDS::TMPFile* PARAVIS_Gen_i::SaveASCII(SALOMEDS::SComponent_ptr theComponent,
+                                          const char* theURL,
+                                          bool isMultiFile) 
+  {
+    return myParaVisGen->Save(theComponent,theURL,isMultiFile);
+  }
+
+
+  //===========================================================================
+  char* PARAVIS_Gen_i::IORToLocalPersistentID(SALOMEDS::SObject_ptr theSObject,
+                                          const char* IORString,
+                                          CORBA::Boolean isMultiFile,
+                                          CORBA::Boolean isASCII) 
+  {
+    return myParaVisGen->IORToLocalPersistentID(theSObject, IORString, isMultiFile, isASCII);
+  }
+
+  //===========================================================================
+  void PARAVIS_Gen_i::ImportFile(const char* theFileName)
+  {
+    if (CORBA::is_nil(myParaVisGen)) {
+      MESSAGE("PARAVIS_Gen_i is null");
+      return;
+    }
+    myParaVisGen->ImportFile(theFileName);
+  }
+
+  //===========================================================================
+  char* PARAVIS_Gen_i::GetTrace()
+  {
+    if (CORBA::is_nil(myParaVisGen)) {
+      MESSAGE("PARAVIS_Gen_i is null");
+      return CORBA::string_dup("");
+    }
+    return CORBA::string_dup(myParaVisGen->GetTrace());
+  }
+
+  //===========================================================================
+  void PARAVIS_Gen_i::SaveTrace(const char* theFileName)
+  {
+    if (CORBA::is_nil(myParaVisGen)) {
+      MESSAGE("PARAVIS_Gen_i is null");
+      return ;
+    }
+    myParaVisGen->SaveTrace(theFileName);
+  }
+
+  //===========================================================================
+  void PARAVIS_Gen_i::Close(SALOMEDS::SComponent_ptr theComponent)
+  {
+    myParaVisGen->Close(theComponent);
+  }
+
+
+  //===========================================================================
+  char* PARAVIS_Gen_i::ComponentDataType()
+  {
+    return CORBA::string_dup("PARAVIS");
+  }
+
+  //===========================================================================
+  CORBA::Boolean PARAVIS_Gen_i::CanPublishInStudy(CORBA::Object_ptr theIOR) 
+  {
+    return myParaVisGen->CanPublishInStudy(theIOR);
+  }
+
+
+  //===========================================================================
+  SALOMEDS::SObject_ptr PARAVIS_Gen_i::PublishInStudy(SALOMEDS::Study_ptr theStudy,
+                                                  SALOMEDS::SObject_ptr theSObject,
+                                                  CORBA::Object_ptr theObject,
+                                                  const char* theName) 
+    throw (SALOME::SALOME_Exception) 
+  {
+    return myParaVisGen->PublishInStudy(theStudy, theSObject, theObject, theName);
+  }
+
+  //===========================================================================
+  CORBA::Boolean PARAVIS_Gen_i::CanCopy(SALOMEDS::SObject_ptr theObject) 
+  {
+    return myParaVisGen->CanCopy(theObject);
+  }
+  
+
+  //===========================================================================
+  SALOMEDS::TMPFile* PARAVIS_Gen_i::CopyFrom(SALOMEDS::SObject_ptr theObject, CORBA::Long& theObjectID) 
+  {
+    return myParaVisGen->CopyFrom(theObject, theObjectID);
+  }
+  
+
+  //===========================================================================
+  CORBA::Boolean PARAVIS_Gen_i::CanPaste(const char* theComponentName, CORBA::Long theObjectID) 
+  {
+    return myParaVisGen->CanPaste(theComponentName, theObjectID);
+  }
+
+  //===========================================================================
+  SALOMEDS::SObject_ptr PARAVIS_Gen_i::PasteInto(const SALOMEDS::TMPFile& theStream,
+                                             CORBA::Long theObjectID,
+                                             SALOMEDS::SObject_ptr theObject) 
+  {
+    return myParaVisGen->PasteInto(theStream,theObjectID,theObject);
+  }
+
+  //===========================================================================
+  PARAVIS::string_array* PARAVIS_Gen_i::GetClassesList()
+  {
+    return myParaVisGen->GetClassesList();
+  }
+
+  //===========================================================================
+  PARAVIS_Base_ptr PARAVIS_Gen_i::CreateClass(const char* theClassName)
+  {
+    return myParaVisGen->CreateClass(theClassName);
+  }
+
+  //===========================================================================
+  void PARAVIS_Gen_i::GetConnectionParameters(CORBA::Long& theId, 
+                                              CORBA::String_out theDHost, CORBA::Long& theDPort,
+                                              CORBA::String_out theRHost, CORBA::Long& theRPort,
+                                              CORBA::Long& theReversed)
+  {
+    myParaVisGen->GetConnectionParameters(theId, theDHost, theDPort, theRHost, theRPort, theReversed);
+  }
+    
+  //===========================================================================
+  void PARAVIS_Gen_i::ActivateModule()
+  {
+    myParaVisGen->ActivateModule();
+  }
+}
diff --git a/src/ENGINE/PARAVIS_Engine_i.hh b/src/ENGINE/PARAVIS_Engine_i.hh
new file mode 100644 (file)
index 0000000..b0feb89
--- /dev/null
@@ -0,0 +1,119 @@
+//  Copyright (C) 2007-2008  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.
+//
+//  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
+//
+#ifndef __PARAVIS_ENGINE_I_H__
+#define __PARAVIS_ENGINE_I_H__
+
+// IDL headers
+#include "SALOMEconfig.h"
+#include CORBA_SERVER_HEADER(PARAVIS_Gen)
+#include CORBA_SERVER_HEADER(SALOME_Session)
+#include CORBA_SERVER_HEADER(SALOMEDS)
+#include CORBA_SERVER_HEADER(SALOMEDS_Attributes)
+
+#include "SALOME_Component_i.hxx"
+
+namespace PARAVIS
+{
+  /*!
+   * Implements PARAVIS_Gen interface. 
+   * Ativates corresponded interface in GUI main thread and redirects all calls to that interface.
+   */
+  class PARAVIS_Gen_i : public virtual POA_PARAVIS::PARAVIS_Gen,
+                    public virtual ::Engines_Component_i
+  {
+    //! Reference on corresponded interface in GUI thread
+    PARAVIS_Gen_var myParaVisGen;
+
+    //! Empty Constructor
+    PARAVIS_Gen_i();
+    //! Copy Constructor
+    PARAVIS_Gen_i(const PARAVIS::PARAVIS_Gen_i &);
+  public:
+    //! Constructor
+    PARAVIS_Gen_i(SALOME::Session_ptr session,
+                  CORBA::ORB_ptr orb,
+                  PortableServer::POA_ptr poa,
+                  PortableServer::ObjectId * contId, 
+                  const char *instanceName, 
+                  const char *interfaceName);
+    virtual ~PARAVIS_Gen_i();
+    
+    virtual char* GetIOR();
+
+    virtual void ImportFile(const char* theFileName);
+    
+    virtual char* GetTrace();
+    
+    virtual void SaveTrace(const char* theFileName);
+    
+    // inherited methods from SALOMEDS::Driver
+    virtual SALOMEDS::TMPFile* Save(SALOMEDS::SComponent_ptr theComponent, 
+                                    const char* theURL, bool isMultiFile);
+    
+    virtual SALOMEDS::TMPFile* SaveASCII(SALOMEDS::SComponent_ptr theComponent,
+                                         const char* theURL, bool isMultiFile);
+    
+    virtual bool Load(SALOMEDS::SComponent_ptr,         const SALOMEDS::TMPFile &,
+                      const char* theURL, bool isMultiFile);
+
+    virtual bool LoadASCII(SALOMEDS::SComponent_ptr, const SALOMEDS::TMPFile &,
+                           const char* theURL, bool isMultiFile);
+    
+    virtual void Close(SALOMEDS::SComponent_ptr IORSComponent);
+
+    virtual char* ComponentDataType();
+
+    virtual char* IORToLocalPersistentID(SALOMEDS::SObject_ptr theSObject, const char* IORString,
+                                         CORBA::Boolean isMultiFile, CORBA::Boolean isASCII);
+
+    virtual char* LocalPersistentIDToIOR(SALOMEDS::SObject_ptr theSObject, const char* aLocalPersistentID,
+                                         CORBA::Boolean isMultiFile, CORBA::Boolean isASCII);
+
+    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 CORBA::Boolean CanCopy(SALOMEDS::SObject_ptr theObject);
+
+    virtual SALOMEDS::TMPFile* CopyFrom(SALOMEDS::SObject_ptr theObject, CORBA::Long& theObjectID);
+
+    virtual CORBA::Boolean CanPaste(const char* theComponentName, CORBA::Long theObjectID);
+
+    virtual SALOMEDS::SObject_ptr PasteInto(const SALOMEDS::TMPFile& theStream,
+                                            CORBA::Long theObjectID, SALOMEDS::SObject_ptr theObject);
+
+
+    virtual PARAVIS::string_array* GetClassesList();
+    virtual PARAVIS_Base_ptr CreateClass(const char* theClassName);
+    virtual void GetConnectionParameters(CORBA::Long& theId, 
+                                         CORBA::String_out theDHost, CORBA::Long& theDPort,
+                                         CORBA::String_out theRHost, CORBA::Long& theRPort,
+                                         CORBA::Long& theReversed);
+                                         
+    virtual void ActivateModule();
+
+  };
+};
+#endif
index c9e363ebe2042fa2db70d90ff047a38f0976a24e..c551160b7e1cd2ea293a514305f81bf059362982 100755 (executable)
@@ -26,8 +26,8 @@
 include $(top_srcdir)/adm_local/unix/make_common_starter.am
 
 if BUILD_PLUGINS
-  SUBDIRS = PVGUI Plugins
+  SUBDIRS = ENGINE PVGUI PV_SWIG Plugins
 else
-  SUBDIRS = PVGUI
+  SUBDIRS = ENGINE PVGUI PV_SWIG
 endif
 
index 564d71f566902201eb7aed0d4e6244619dacc20d..87cd33a929e03591344994afbac09c56db160fc4 100644 (file)
 
 include $(top_srcdir)/adm_local/unix/make_common_starter.am
 
+#Executable
+bin_PROGRAMS = vtkWrapIDL_HH vtkWrapIDL_CC
+
+dist_vtkWrapIDL_HH_SOURCES = ${PVHOME}/src/vtkParse.tab.c $(top_srcdir)/idl/vtkWrapIDL.c
+dist_vtkWrapIDL_CC_SOURCES = ${PVHOME}/src/vtkParse.tab.c $(top_srcdir)/idl/vtkWrapIDL.c
+
+vtkWrapIDL_HH_CPPFLAGS = -DIDL_I_HH    ${PARAVIEW_INCLUDES}
+
+
+vtkWrapIDL_CC_CPPFLAGS = -DIDL_I_CC    ${PARAVIEW_INCLUDES}
+
+include $(srcdir)/wrap.am
+
 # Library target
 lib_LTLIBRARIES = libPARAVIS.la
 
@@ -44,38 +57,87 @@ dist_libPARAVIS_la_SOURCES =        \
        PVGUI_ViewWindow.h \
        PVGUI_ViewWindow.cxx \
        PVGUI_OutputWindowAdapter.h \
-       PVGUI_OutputWindowAdapter.cxx
+       PVGUI_OutputWindowAdapter.cxx \
+       PVGUI_Tools.h \
+       PVGUI_Tools.cxx \
+       PVGUI_Trace.h \
+       PVGUI_Trace.cxx \
+       PV_I.h \
+       PARAVIS_Gen_i.hh \
+       PV_Events.h \
+       PV_Tools.h \
+       PARAVIS_Gen_i.cc \
+       PV_Tools.cxx \
+       $(WRAP_IDL_I_HH) \
+       $(WRAP_IDL_I_CC) \
+       PARAVIS_CreateClass.cxx
 
 # MOC pre-processing
 MOC_FILES = \
        PVGUI_Module_moc.cxx \
        PVGUI_ViewManager_moc.cxx \
        PVGUI_ViewModel_moc.cxx \
-       PVGUI_ViewWindow_moc.cxx
+       PVGUI_ViewWindow_moc.cxx \
+       PVGUI_Trace_moc.cxx
 
 nodist_libPARAVIS_la_SOURCES = $(MOC_FILES)
 
 # additionnal compilation flags
 # Note that ParaView uses HDF5
 libPARAVIS_la_CPPFLAGS = \
+       -ftemplate-depth-32 \
        $(HDF5_INCLUDES) \
        $(QT_INCLUDES) \
        $(QT_ASSISTANT_INCLUDES) \
        $(PARAVIEW_INCLUDES) \
        $(CAS_CPPFLAGS) \
        $(PYTHON_INCLUDES) \
-       $(GUI_CXXFLAGS)
+       @CAS_CPPFLAGS@ @CAS_CXXFLAGS@ \
+       $(KERNEL_CXXFLAGS) \
+       $(CORBA_CXXFLAGS) $(CORBA_INCLUDES) \
+       $(GUI_CXXFLAGS) \
+       $(VISU_CXXFLAGS) \
+       $(MED_CXXFLAGS) \
+       -I$(top_builddir)/idl \
+       -I$(srcdir)/../../idl   \
+       -I$(top_builddir)/salome_adm/unix
 
 # additionnal linkage flags
 # Note that ParaView uses HDF5
 libPARAVIS_la_LDFLAGS = \
+       $(PYTHON_LIBS) \
+       $(QT_MT_LIBS) \
        $(HDF5_LIBS) \
        $(QT_ASSISTANT_LIBS) \
        $(PARAVIEW_LIBS) \
-       $(GUI_LDFLAGS) \
-       -lLightApp 
+       ../../idl/libSalomeIDLPARAVIS.la \
+       $(KERNEL_LDFLAGS) -lSalomeNS -lSalomeDSClient -lSalomeContainer -lSalomeLifeCycleCORBA \
+       $(GUI_LDFLAGS) -lSalomeApp -lLightApp \
+       $(VISU_LDFLAGS) -lSalomeIDLVISU
+
+libPARAVIS_la_LIBADD= \
+       -lSalomeIDLKernel \
+       -lSalomeHDFPersist \
+       -lSalomeGenericObj \
+       -lSalomeContainer \
+       -lSalomeCommunication \
+       -lSalomeNS \
+       -lTOOLSDS \
+       -lOpUtil \
+       -lSalomeLifeCycleCORBA \
+       -lEvent \
+       -lSalomeApp \
+       -lSalomeSession \
+       -lqtx \
+       -lLightApp
 
+#      
 # resources files
 nodist_salomeres_DATA = \
            PARAVIS_images.qm \
            PARAVIS_msg_en.qm
+
+mostlyclean-local: clean-wrap
+
+clean-wrap:
+       -rm -f *.hh *.cc
diff --git a/src/PVGUI/PARAVIS_Gen_i.cc b/src/PVGUI/PARAVIS_Gen_i.cc
new file mode 100644 (file)
index 0000000..eadc681
--- /dev/null
@@ -0,0 +1,553 @@
+//  Copyright (C) 2007-2008  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.
+//
+//  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
+//
+//  PARAVIS OBJECT : interactive object for PARAVIS entities implementation
+//  File   : PARAVIS_Gen_i.cc
+//  Author : Vitaly Smetannikov
+//  Module : PARAVIS
+//
+
+
+#include "PARAVIS_Gen_i.hh"
+
+// IDL Headers
+#include <omnithread.h>
+#include CORBA_SERVER_HEADER(SALOME_Session)
+#include CORBA_SERVER_HEADER(SALOME_ModuleCatalog)
+
+#include <CAM_Module.h>
+#include "PVGUI_Module.h"
+#include <SalomeApp_Application.h>
+
+#include <SALOMEDS_Tool.hxx>
+#include <QFileInfo>
+
+#include "PV_Events.h"
+#include "PV_Tools.h"
+
+#include "QDomDocument"
+#include "QDomNode"
+#include "QDomElement"
+#include "QFile"
+#include "QTextStream"
+
+#include "vtkWrapIDL.h"
+
+#include <pqServer.h>
+#include <pqServerResource.h>
+
+
+#ifdef _DEBUG_
+static int MYDEBUG = 1;
+#else
+static int MYDEBUG = 0;
+#endif
+
+using namespace std;
+
+extern PARAVIS::PARAVIS_Base_i* CreateInstance(::vtkObjectBase* Inst, const QString&);
+
+extern "C" 
+PARAVIS_I_EXPORT PARAVIS::PARAVIS_Gen_ptr GetImpl(CORBA::ORB_ptr theORB, 
+                                                  PortableServer::POA_ptr thePOA,
+                                                  SALOME_NamingService* theNamingService,
+                                                  QMutex* theMutex)
+{
+  if(MYDEBUG) MESSAGE("extern 'C' GetImpl");
+  PARAVIS::PARAVIS_Gen_i *aPARAVIS_Gen = new PARAVIS::PARAVIS_Gen_i(theORB, 
+                                                                    thePOA, 
+                                                                    theNamingService, 
+                                                                    theMutex);
+  return aPARAVIS_Gen->_this();
+}
+
+
+
+namespace PARAVIS
+{
+  PARAVIS_Base_i::~PARAVIS_Base_i() {
+    if(mySmartPointer != NULL) mySmartPointer->Delete();
+  }
+
+  void PARAVIS_Base_i::Init(::vtkObjectBase* base) {
+    if (mySmartPointer != NULL) mySmartPointer->Delete();
+    mySmartPointer = base;
+  }
+
+  ::vtkObjectBase* PARAVIS_Base_i::getVTKObject(PARAVIS_Base_ptr theBase) {
+    PARAVIS_Base_i* aBase = GET_SERVANT(theBase);
+    return (aBase != NULL)? aBase->getVTKObject() : NULL;
+  }
+
+  CORBA::Boolean PARAVIS_Base_i::IsSame(PARAVIS_Base_ptr theOther)
+  {
+    PARAVIS_Base_i* aBase = GET_SERVANT(theOther);
+    if (aBase == NULL) 
+      return false;
+    return mySmartPointer.GetPointer() == aBase->getVTKObject();
+  }
+
+
+
+
+  PARAVIS_Gen_i*          PARAVIS_Gen_i::myParavisGenImpl;
+  CORBA::ORB_var          PARAVIS_Gen_i::myOrb;
+  PortableServer::POA_var PARAVIS_Gen_i::myPoa;
+  SALOME_LifeCycleCORBA*  PARAVIS_Gen_i::myEnginesLifeCycle;
+  SALOME_NamingService*   PARAVIS_Gen_i::myNamingService;
+  QMutex*                 PARAVIS_Gen_i::myMutex;
+  SalomeApp_Application*  PARAVIS_Gen_i::mySalomeApp = 0;
+
+
+  //----------------------------------------------------------------------------
+  PARAVIS_Gen_i::PARAVIS_Gen_i(CORBA::ORB_ptr theORB, PortableServer::POA_ptr thePOA,
+                               SALOME_NamingService* theNamingService, QMutex* theMutex) :
+    Engines_Component_i()
+  {
+    if(MYDEBUG) MESSAGE("PARAVIS_Gen_i::PARAVIS_Gen_i");
+    if (mySalomeApp) return;
+
+    myMutex = theMutex;
+    myOrb = CORBA::ORB::_duplicate(theORB);
+    myPoa = PortableServer::POA::_duplicate(thePOA);
+    myParavisGenImpl = this;
+    myNamingService = theNamingService;
+
+    static SALOME_LifeCycleCORBA aEnginesLifeCycle(theNamingService);
+    myEnginesLifeCycle = &aEnginesLifeCycle;
+
+    CORBA::Object_var anObj = myNamingService->Resolve("/myStudyManager");
+    if (!CORBA::is_nil(anObj)) {
+      SALOMEDS::StudyManager_var aStudyManager = SALOMEDS::StudyManager::_narrow(anObj);
+      SALOMEDS::ListOfOpenStudies_var aListOfOpenStudies = aStudyManager->GetOpenStudies();
+      if(aListOfOpenStudies->length() > 0) {
+        CORBA::String_var aStudyName = aListOfOpenStudies[0];
+        myStudyDocument = aStudyManager->GetStudyByName(aStudyName);
+        if (!myStudyDocument->_is_nil()) {
+          mySalomeApp = ProcessEvent(new TGetGUIApplication(myStudyDocument->StudyId()));
+          if(!myStudyDocument->GetProperties()->IsLocked())
+            FindOrCreateParaVisComponent(myStudyDocument);
+        }
+      } else
+        if(MYDEBUG) MESSAGE("PARAVIS_Gen_i::PARAVIS_Gen_i : there is no opened study in StudyManager !!!");
+    } else
+      if(MYDEBUG) MESSAGE("PARAVIS_Gen_i::PARAVIS_Gen_i : Can't find StudyManager !!!");
+
+  }
+
+  //----------------------------------------------------------------------------
+  PARAVIS_Gen_i::~PARAVIS_Gen_i()
+  {
+    if(MYDEBUG) MESSAGE("PARAVIS_Gen_i::~PARAVIS_Gen_i");
+  }
+
+  //----------------------------------------------------------------------------
+  char* PARAVIS_Gen_i::GetIOR()
+  {
+    if(myIOR == ""){
+      CORBA::Object_var anObject = _this();
+      CORBA::String_var anIOR = myOrb->object_to_string(anObject);
+      myIOR = anIOR.in();
+    }
+    return CORBA::string_dup(myIOR.c_str());
+  }
+
+  //----------------------------------------------------------------------------
+  void PARAVIS_Gen_i::ImportFile(const char* theFileName)
+  {
+    if(MYDEBUG) MESSAGE("PARAVIS_Gen_i::ImportFile: " <<theFileName);
+    ProcessVoidEvent(new TImportFile(mySalomeApp, theFileName));
+  }
+
+  //----------------------------------------------------------------------------
+  char* PARAVIS_Gen_i::GetTrace()
+  {
+    if(MYDEBUG) MESSAGE("PARAVIS_Gen_i::PrintTrace: ");
+    return CORBA::string_dup(ProcessEvent(new TGetTrace(mySalomeApp)));
+  }
+
+  //----------------------------------------------------------------------------
+  void PARAVIS_Gen_i::SaveTrace(const char* theFileName)
+  {
+    if(MYDEBUG) MESSAGE("PARAVIS_Gen_i::SaveTrace: " <<theFileName);
+    ProcessVoidEvent(new TSaveTrace(mySalomeApp, theFileName));
+  }
+
+  //----------------------------------------------------------------------------
+  void processElements(QDomNode& thePropertyNode, QStringList& theFileNames, const char* theNewPath)
+  {
+    QDomNode aElementNode = thePropertyNode.firstChild();
+    while (aElementNode.isElement()) {
+      QDomElement aElement = aElementNode.toElement();
+      if (aElement.tagName() == "Element") {
+        QString aIndex = aElement.attribute("index");
+        if (aIndex == "0") {
+          QString aValue = aElement.attribute("value");
+          if (!aValue.isNull()) {
+            if (theNewPath == 0) {
+              QFileInfo aFInfo(aValue);
+              theFileNames<<aValue;
+              aElement.setAttribute("value", aFInfo.fileName());
+              break;
+            } else {
+              aElement.setAttribute("value", QString(theNewPath) + aValue);            
+            }
+          }
+        }
+      }
+      aElementNode = aElementNode.nextSibling();
+    }
+  }
+
+
+  //----------------------------------------------------------------------------
+  void processProperties(QDomNode& theProxyNode, QStringList& theFileNames, const char* theNewPath)
+  {
+    QDomNode aPropertyNode = theProxyNode.firstChild();
+    while (aPropertyNode.isElement()) {
+      QDomElement aProperty = aPropertyNode.toElement();
+      QString aName = aProperty.attribute("name");
+      if ((aName == "FileName") || (aName == "FileNameInfo") || (aName == "FileNames")) {
+        processElements(aPropertyNode, theFileNames, theNewPath);
+      }
+      aPropertyNode = aPropertyNode.nextSibling();
+    }
+  }  
+
+
+  //----------------------------------------------------------------------------
+  void processProxies(QDomNode& theNode, QStringList& theFileNames, const char* theNewPath)
+  {
+    QDomNode aProxyNode = theNode.firstChild();
+    while (aProxyNode.isElement()) {
+      QDomElement aProxy = aProxyNode.toElement();
+      if (aProxy.tagName() == "Proxy") {
+        QString aGroup = aProxy.attribute("group");
+        if (aGroup == "sources") {
+          processProperties(aProxyNode, theFileNames, theNewPath);
+        }
+      }
+      aProxyNode = aProxyNode.nextSibling();
+    }
+  }
+
+  //----------------------------------------------------------------------------
+  bool processAllFilesInState(const char* aFileName, QStringList& theFileNames, const char* theNewPath)
+  {
+    QFile aFile(aFileName);
+    if (!aFile.open(QFile::ReadOnly)) {
+      MESSAGE("Can't open state file "<<aFileName);
+      return false;
+    }
+    QDomDocument aDoc;
+    bool aRes = aDoc.setContent(&aFile);
+    aFile.close();
+    
+    if (!aRes) {
+      MESSAGE("File "<<aFileName<<" is not XML document");
+      return false;
+    }
+    
+    QDomElement aRoot = aDoc.documentElement();
+    if ( aRoot.isNull() || aRoot.tagName() != "ParaView" ) {
+      MESSAGE( "Invalid XML root" );
+      return false;
+    }
+
+    QDomNode aNode = aRoot.firstChild();
+    while (aRes  && !aNode.isNull() ) {
+      aRes = aNode.isElement();
+      if ( aRes ) {
+        QDomElement aSection = aNode.toElement();
+        if (aSection.tagName() == "ServerManagerState") {
+          processProxies(aNode, theFileNames, theNewPath);
+        }
+      }
+      aNode = aNode.nextSibling();
+    }
+    if (!aFile.open(QFile::WriteOnly | QFile::Truncate)) {
+      MESSAGE("Can't open state file "<<aFileName<<" for writing");
+      return false;
+    }
+    QTextStream out(&aFile);
+    aDoc.save(out, 2);
+    aFile.close();
+    
+    return true;
+  }
+
+
+  //----------------------------------------------------------------------------
+  SALOMEDS::TMPFile* PARAVIS_Gen_i::Save(SALOMEDS::SComponent_ptr theComponent, 
+                                         const char* theURL, bool isMultiFile)
+  {
+    if(MYDEBUG) MESSAGE("PARAVIS_Gen_i::Save - theURL = '"<<theURL<<"'");
+
+    std::string aTmpDir = SALOMEDS_Tool::GetTmpDir();
+
+    std::ostringstream aStream;
+    aStream<<"paravisstate:"<<(long)this;
+    std::string aFileName = "_" + aStream.str();
+    if(MYDEBUG) MESSAGE("aFileName = '"<<aFileName);
+
+    //std::vector<std::string> aFileNames;
+    //aFileNames.push_back(aFileName);
+
+    SALOMEDS::TMPFile_var aStreamFile = new SALOMEDS::TMPFile(0);
+
+    std::string aFile = aTmpDir + aFileName;
+    ProcessVoidEvent(new TSaveStateFile(mySalomeApp, aFile.c_str()));
+
+    // TO Do: Collect all files from state
+    QStringList aFileNames;
+    processAllFilesInState(aFile.c_str(), aFileNames, 0);
+    aFileNames<<QString(aFile.c_str());
+
+    QStringList aNames;
+    foreach(QString aFile, aFileNames) {
+      QFileInfo aInfo(aFile);
+      aNames<<aInfo.fileName();
+    }
+    
+    SALOMEDS::ListOfFileNames_var aListOfFileNames = GetListOfFileNames(aFileNames);
+    SALOMEDS::ListOfFileNames_var aListOfNames = GetListOfFileNames(aNames);
+
+    aStreamFile = SALOMEDS_Tool::PutFilesToStream(aListOfFileNames.in(), aListOfNames.in());
+    SALOMEDS_Tool::RemoveTemporaryFiles(theURL, aListOfFileNames, true);
+
+    return aStreamFile._retn();
+  }
+    
+  //----------------------------------------------------------------------------
+  SALOMEDS::TMPFile* PARAVIS_Gen_i::SaveASCII(SALOMEDS::SComponent_ptr theComponent,
+                                              const char* theURL, bool isMultiFile)
+  {
+    if(MYDEBUG) MESSAGE("PARAVIS_Gen_i::Save - theURL = '"<<theURL<<"'");
+
+    std::string aTmpDir = SALOMEDS_Tool::GetTmpDir();
+
+    std::ostringstream aStream;
+    aStream<<"paravisstate:"<<(long)this;
+    std::string aFileName = "_" + aStream.str();
+    if(MYDEBUG) MESSAGE("aFileName = '"<<aFileName);
+
+    SALOMEDS::TMPFile_var aStreamFile = new SALOMEDS::TMPFile(0);
+
+    std::string aFile = aTmpDir + aFileName;
+    ProcessVoidEvent(new TSaveStateFile(mySalomeApp, aFile.c_str()));
+
+    //Collect all files from state
+    QStringList aFileNames;
+    processAllFilesInState(aFile.c_str(), aFileNames, 0);
+    aFileNames<<QString(aFile.c_str());
+
+    QStringList aNames;
+    foreach(QString aFile, aFileNames) {
+      QFileInfo aInfo(aFile);
+      aNames<<aInfo.fileName();
+    }
+    
+    SALOMEDS::ListOfFileNames_var aListOfFileNames = GetListOfFileNames(aFileNames);
+    SALOMEDS::ListOfFileNames_var aListOfNames = GetListOfFileNames(aNames);
+
+    aStreamFile = SALOMEDS_Tool::PutFilesToStream(aListOfFileNames.in(), aListOfNames.in());
+    SALOMEDS_Tool::RemoveTemporaryFiles(theURL, aListOfFileNames, true);
+
+    return aStreamFile._retn();
+  }
+    
+
+  //----------------------------------------------------------------------------
+  bool PARAVIS_Gen_i::Load(SALOMEDS::SComponent_ptr theComponent,       const SALOMEDS::TMPFile& theStream,
+                           const char* theURL, bool isMultiFile)
+  {
+    std::string aTmpDir = isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir();
+    if(MYDEBUG) MESSAGE("PARAVIS_Gen_i::Load - "<<aTmpDir);
+
+    SALOMEDS::ListOfFileNames_var aSeq = SALOMEDS_Tool::PutStreamToFiles(theStream, aTmpDir, false);
+    if (aSeq->length() == 0)
+      return false;
+
+    std::string aFile = aTmpDir + std::string(aSeq[aSeq->length() - 1]);
+    QStringList aEmptyList;
+    processAllFilesInState(aFile.c_str(), aEmptyList, aTmpDir.c_str());
+    ProcessVoidEvent(new TLoadStateFile(mySalomeApp, aFile.c_str()));
+
+    return true;
+  }
+
+  //----------------------------------------------------------------------------
+  bool PARAVIS_Gen_i::LoadASCII(SALOMEDS::SComponent_ptr theComponent, 
+                                const SALOMEDS::TMPFile& theStream,
+                                const char* theURL, bool isMultiFile)
+  {
+    std::string aTmpDir = isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir();
+    if(MYDEBUG) MESSAGE("PARAVIS_Gen_i::Load - "<<aTmpDir);
+
+    SALOMEDS::ListOfFileNames_var aSeq = SALOMEDS_Tool::PutStreamToFiles(theStream, aTmpDir, false);
+    if (aSeq->length() == 0)
+      return false;
+
+    std::string aFile = aTmpDir + std::string(aSeq[aSeq->length() - 1]);
+    QStringList aEmptyList;
+    processAllFilesInState(aFile.c_str(), aEmptyList, aTmpDir.c_str());
+    ProcessVoidEvent(new TLoadStateFile(mySalomeApp, aFile.c_str()));
+
+    return true;
+  }
+    
+  //----------------------------------------------------------------------------
+  void PARAVIS_Gen_i::Close(SALOMEDS::SComponent_ptr IORSComponent)
+  {
+  }
+  
+  //----------------------------------------------------------------------------
+  char* PARAVIS_Gen_i::ComponentDataType()
+  {
+    return CORBA::string_dup("PARAVIS");
+  }
+
+  //----------------------------------------------------------------------------
+  char* PARAVIS_Gen_i::IORToLocalPersistentID(SALOMEDS::SObject_ptr theSObject, const char* IORString,
+                                              CORBA::Boolean isMultiFile, CORBA::Boolean isASCII)
+  {
+    CORBA::String_var aString("");
+    return aString._retn();
+  }
+
+  //----------------------------------------------------------------------------
+  char* PARAVIS_Gen_i::LocalPersistentIDToIOR(SALOMEDS::SObject_ptr theSObject, 
+                                              const char* aLocalPersistentID,
+                                              CORBA::Boolean isMultiFile, 
+                                              CORBA::Boolean isASCII)
+  {
+    CORBA::String_var aString("");
+    return aString._retn();
+  }
+
+  //----------------------------------------------------------------------------
+  bool PARAVIS_Gen_i::CanPublishInStudy(CORBA::Object_ptr theIOR)
+  {
+    return false;
+  }
+
+  //----------------------------------------------------------------------------
+  SALOMEDS::SObject_ptr PARAVIS_Gen_i::PublishInStudy(SALOMEDS::Study_ptr theStudy,
+                                                      SALOMEDS::SObject_ptr theSObject, 
+                                                      CORBA::Object_ptr theObject,
+                                                      const char* theName) 
+    throw (SALOME::SALOME_Exception)
+  {
+    SALOMEDS::SObject_var aResultSO;
+    return aResultSO._retn();
+  }
+
+  //----------------------------------------------------------------------------
+  CORBA::Boolean PARAVIS_Gen_i::CanCopy(SALOMEDS::SObject_ptr theObject)
+  {
+    return false;
+  }
+
+  //----------------------------------------------------------------------------
+  SALOMEDS::TMPFile* PARAVIS_Gen_i::CopyFrom(SALOMEDS::SObject_ptr theObject, CORBA::Long& theObjectID)
+  {
+    SALOMEDS::TMPFile_var aStreamFile = new SALOMEDS::TMPFile;
+    return aStreamFile._retn();
+  }
+
+  //----------------------------------------------------------------------------
+  CORBA::Boolean PARAVIS_Gen_i::CanPaste(const char* theComponentName, CORBA::Long theObjectID)
+  {
+    return false;
+  }
+
+  //----------------------------------------------------------------------------
+  SALOMEDS::SObject_ptr PARAVIS_Gen_i::PasteInto(const SALOMEDS::TMPFile& theStream,
+                                                 CORBA::Long theObjectID, SALOMEDS::SObject_ptr theObject)
+  {
+    return SALOMEDS::SObject::_nil();
+  }
+
+  //----------------------------------------------------------------------------
+  PARAVIS::string_array* PARAVIS_Gen_i::GetClassesList()
+  {
+    int k;
+    for (k = 0; strcmp(wrapped_classes[k], "") != 0; k++);
+    PARAVIS::string_array_var aNames = new PARAVIS::string_array();
+    aNames->length(k);
+    for (CORBA::ULong i = 0; i < k; i++)
+      aNames[i] = CORBA::string_dup(wrapped_classes[i]);
+    return aNames._retn();
+  }
+
+  //----------------------------------------------------------------------------
+  PARAVIS_Base_ptr PARAVIS_Gen_i::CreateClass(const char* theClassName)
+  {
+    PARAVIS::PARAVIS_Base_i* aClass = CreateInstance(NULL, QString(theClassName));
+    return aClass->_this();
+  }
+
+  //----------------------------------------------------------------------------
+  void PARAVIS_Gen_i::GetConnectionParameters(CORBA::Long& theId, 
+                                              CORBA::String_out theDHost, CORBA::Long& theDPort,
+                                              CORBA::String_out theRHost, CORBA::Long& theRPort,
+                                              CORBA::Long& theReversed)
+  {
+    pqServer* aServer = ProcessEvent(new TGetActiveServer(mySalomeApp));
+    if (aServer) {
+      theId = static_cast<int>(aServer->GetConnectionID());
+
+      pqServerResource serverRes = aServer->getResource();
+      theReversed = (serverRes.scheme() == "csrc" || serverRes.scheme() == "cdsrsrc")? 1 : 0;
+
+      theDPort = serverRes.dataServerPort() < 0? serverRes.port() : serverRes.dataServerPort();
+      theRPort = serverRes.renderServerPort() < 0 ? 0 : serverRes.renderServerPort();
+
+      QString dsHost = serverRes.dataServerHost().isEmpty()? serverRes.host() : serverRes.dataServerHost();
+      QString rsHost = serverRes.renderServerHost();
+
+      theDHost = CORBA::string_dup(qPrintable(dsHost));
+      theRHost = CORBA::string_dup(qPrintable(rsHost));
+    }
+  }
+
+
+  //----------------------------------------------------------------------------
+  Engines::TMPFile* PARAVIS_Gen_i::DumpPython(CORBA::Object_ptr theStudy,
+                                              CORBA::Boolean theIsPublished,
+                                              CORBA::Boolean& theIsValidScript)
+  {
+    theIsValidScript = true;
+    std::string aResult(ProcessEvent(new TGetTrace(mySalomeApp)));
+    aResult += "\ndef RebuildData(theStudy):\n  pass\n";
+    CORBA::ULong aSize = aResult.size() + 1;
+    char* aBuffer = new char[aSize];
+    strcpy(aBuffer, &aResult[0]);
+    Engines::TMPFile_var aDump = new Engines::TMPFile(aSize,aSize,(CORBA::Octet*)aBuffer,1);
+    return aDump._retn();
+  }
+
+  //----------------------------------------------------------------------------
+  void PARAVIS_Gen_i::ActivateModule()
+  {
+    ProcessVoidEvent(new TActivateModule(mySalomeApp));
+  }
+}
diff --git a/src/PVGUI/PARAVIS_Gen_i.hh b/src/PVGUI/PARAVIS_Gen_i.hh
new file mode 100644 (file)
index 0000000..91b3746
--- /dev/null
@@ -0,0 +1,211 @@
+//  Copyright (C) 2007-2008  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.
+//
+//  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   : PARAVIS_Gen_i.hh
+//  Author : Vitaly Smetannikov
+//  Module : PARAVIS
+//
+#ifndef __PARAVIS_GEN_I_H__
+#define __PARAVIS_GEN_I_H__
+
+#include "PV_I.h"
+#include "vtkSmartPointer.h"
+
+#include "SALOMEconfig.h"
+#include CORBA_SERVER_HEADER(PARAVIS_Gen)
+#include CORBA_SERVER_HEADER(SALOMEDS)
+#include CORBA_SERVER_HEADER(SALOMEDS_Attributes)
+
+#include "SALOME_NamingService.hxx"
+#include "SALOME_LifeCycleCORBA.hxx"
+
+#include "SALOME_Component_i.hxx"
+#include "SALOME_NamingService.hxx"
+
+#include "vtkSmartPointer.h"
+
+// QT Includes
+#include <QMutex>
+
+class SalomeApp_Application;
+class PVGUI_Module;
+class vtkObjectBase;
+
+namespace PARAVIS
+{
+
+  /*!
+   * Base implementation for all container objects for Paravis serevrmanager API classes
+   */
+  class PARAVIS_Base_i : public virtual POA_PARAVIS::PARAVIS_Base
+  {
+  public:
+    //! Constructor
+    PARAVIS_Base_i() {};
+
+    //! Destructor
+    virtual ~PARAVIS_Base_i();
+
+    //! Initialises internal pointer on existing Paraview class instance
+    virtual void Init(::vtkObjectBase* base);
+
+    //! Returns pointer on internal Paraview class instance
+    virtual ::vtkObjectBase* getVTKObject() { return mySmartPointer.GetPointer(); }
+
+    //! The same as previous in static context
+    static ::vtkObjectBase* getVTKObject(PARAVIS_Base_ptr theBase);
+
+    //! Compares two container objects comparing of their internal pointers
+    virtual CORBA::Boolean IsSame(PARAVIS_Base_ptr theOther);
+
+  protected:
+
+    //! Pointer on wrapped class
+    vtkSmartPointer< ::vtkObjectBase> mySmartPointer;
+  };
+
+  //----------------------------------------------------------------------------
+  class PARAVIS_Gen_i : public virtual POA_PARAVIS::PARAVIS_Gen,
+                    public virtual ::Engines_Component_i
+  {
+    //! Copy constructor
+    PARAVIS_Gen_i(const PARAVIS::PARAVIS_Gen_i &);
+  public:
+    
+    //! Constructor
+    PARAVIS_Gen_i(CORBA::ORB_ptr theORB,
+                  PortableServer::POA_ptr thePOA,
+                  SALOME_NamingService* theNamingService, 
+                  QMutex* theMutex);
+    
+    //! Destructor
+    virtual ~PARAVIS_Gen_i();
+    
+    //! Returns CORBA ID for the current instance
+    virtual char* GetIOR();
+
+    //! Import file to PARAVIS module by its name. 
+    virtual void ImportFile(const char* theFileName);
+    
+    //! Returns Trace string. If Trace is not activated then empty string is returned
+    virtual char* GetTrace();
+
+    //! Save trace sting to a disk file.
+    virtual void SaveTrace(const char* theFileName);
+
+    //! inherited methods from Engines::Component
+    virtual Engines::TMPFile* DumpPython(CORBA::Object_ptr theStudy,
+                                         CORBA::Boolean theIsPublished,
+                                         CORBA::Boolean& theIsValidScript);
+
+    //! inherited methods from SALOMEDS::Driver
+    virtual SALOMEDS::TMPFile* Save(SALOMEDS::SComponent_ptr theComponent, 
+                                    const char* theURL, bool isMultiFile);
+    
+    //! inherited methods from SALOMEDS::Driver
+    virtual SALOMEDS::TMPFile* SaveASCII(SALOMEDS::SComponent_ptr theComponent,
+                                         const char* theURL, bool isMultiFile);
+    
+    //! inherited methods from SALOMEDS::Driver
+    virtual bool Load(SALOMEDS::SComponent_ptr,         const SALOMEDS::TMPFile &,
+                      const char* theURL, bool isMultiFile);
+
+    //! inherited methods from SALOMEDS::Driver
+    virtual bool LoadASCII(SALOMEDS::SComponent_ptr, const SALOMEDS::TMPFile &,
+                           const char* theURL, bool isMultiFile);
+    
+    //! inherited methods from SALOMEDS::Driver
+    virtual void Close(SALOMEDS::SComponent_ptr IORSComponent);
+
+    //! inherited methods from SALOMEDS::Driver
+    virtual char* ComponentDataType();
+
+    //! inherited methods from SALOMEDS::Driver
+    virtual char* IORToLocalPersistentID(SALOMEDS::SObject_ptr theSObject, const char* IORString,
+                                         CORBA::Boolean isMultiFile, CORBA::Boolean isASCII);
+
+    //! inherited methods from SALOMEDS::Driver
+    virtual char* LocalPersistentIDToIOR(SALOMEDS::SObject_ptr theSObject, const char* aLocalPersistentID,
+                                         CORBA::Boolean isMultiFile, CORBA::Boolean isASCII);
+
+    //! inherited methods from SALOMEDS::Driver. Alwais returns false for this module
+    virtual bool CanPublishInStudy(CORBA::Object_ptr theIOR);
+
+    //! inherited methods from SALOMEDS::Driver. Does nothing
+    virtual SALOMEDS::SObject_ptr PublishInStudy(SALOMEDS::Study_ptr theStudy,
+                                                 SALOMEDS::SObject_ptr theSObject, 
+                                                 CORBA::Object_ptr theObject,
+                                                 const char* theName) throw (SALOME::SALOME_Exception);
+
+    //! inherited methods from SALOMEDS::Driver. Alwais returns false for this module
+    virtual CORBA::Boolean CanCopy(SALOMEDS::SObject_ptr theObject);
+
+    //! inherited methods from SALOMEDS::Driver. Does nothing
+    virtual SALOMEDS::TMPFile* CopyFrom(SALOMEDS::SObject_ptr theObject, CORBA::Long& theObjectID);
+
+    //! inherited methods from SALOMEDS::Driver. Does nothing
+    virtual CORBA::Boolean CanPaste(const char* theComponentName, CORBA::Long theObjectID);
+
+    //! inherited methods from SALOMEDS::Driver. Does nothing
+    virtual SALOMEDS::SObject_ptr PasteInto(const SALOMEDS::TMPFile& theStream,
+                                            CORBA::Long theObjectID, SALOMEDS::SObject_ptr theObject);
+
+    //! Implementation of PARAVIS_Gen interface
+    virtual PARAVIS::string_array* GetClassesList();
+
+    //! Implementation of PARAVIS_Gen interface
+    virtual PARAVIS_Base_ptr CreateClass(const char* theClassName);
+
+    //! Implementation of PARAVIS_Gen interface
+    virtual void GetConnectionParameters(CORBA::Long& theId, 
+                                         CORBA::String_out theDHost, CORBA::Long& theDPort,
+                                         CORBA::String_out theRHost, CORBA::Long& theRPort,
+                                         CORBA::Long& theReversed);
+
+
+    //! Implementation of PARAVIS_Gen interface
+    virtual void ActivateModule();
+
+    //! Returns current ORB
+    static CORBA::ORB_var GetORB() { return myOrb;}
+
+    //! Returns current POA
+    static PortableServer::POA_var GetPOA() { return myPoa;}
+
+    //! Returns current implementation instance
+    static PARAVIS_Gen_i* GetParavisGenImpl() { return myParavisGenImpl;}
+
+  private:
+    static CORBA::ORB_var          myOrb;
+    static PortableServer::POA_var myPoa;
+    static PARAVIS_Gen_i*          myParavisGenImpl;
+    static SALOME_LifeCycleCORBA*  myEnginesLifeCycle;
+    static SALOME_NamingService*   myNamingService;
+    static QMutex*                 myMutex;
+
+    std::string         myIOR;
+    SALOMEDS::Study_var myStudyDocument;
+    static SalomeApp_Application* mySalomeApp;
+
+  };
+
+};
+#endif
index 3c5ef3c610e5c59d3152d5ebed04ae6aaeed6678..7476a08a60b14f69e6b66ebe212fe63308514f3e 100644 (file)
 //
 
 #include "PVGUI_Module.h"
+
+#include "SALOMEconfig.h"
+#include CORBA_CLIENT_HEADER(VISU_Gen)
+#include CORBA_SERVER_HEADER(SALOMEDS)
+
+
+#include "PARAVIS_Gen_i.hh"
+
 #include "PVGUI_Module_impl.h"
 #include "PVGUI_ProcessModuleHelper.h"
 #include "PVGUI_ViewModel.h"
 #include "PVGUI_ViewManager.h"
 #include "PVGUI_ViewWindow.h"
+#include "PVGUI_Tools.h"
+#include "PVGUI_Trace.h"
 
 #include <SUIT_Desktop.h>
 #include <SUIT_MessageBox.h>
 #include <SUIT_ResourceMgr.h>
 #include <SUIT_Session.h>
-#include <LightApp_Application.h>
+#include <SUIT_OverrideCursor.h>
+
+// SALOME Includes
+#include "SALOME_LifeCycleCORBA.hxx"
+#include "SALOME_ListIteratorOfListIO.hxx"
+#include "SALOMEDS_SObject.hxx"
+
+//#include <LightApp_Application.h>
 #include <LightApp_SelectionMgr.h>
+#include <SalomeApp_Application.h>
+#include <SalomeApp_Study.h>
+#include <SALOME_ListIO.hxx>
+#include <SALOMEDS_Tool.hxx>
+
 #include <QtxActionMenuMgr.h>
 #include <QtxActionToolMgr.h>
 
@@ -54,7 +76,6 @@
 #include <QToolBar>
 
 #include <pqApplicationCore.h>
-#include <pqActiveServer.h>
 #include <pqActiveView.h>
 #include <pqClientAboutDialog.h>
 #include <pqObjectBuilder.h>
 #include <pqRenderView.h>
 #include <pqRubberBandHelper.h>
 #include <pqServer.h>
-#include <pqServerManagerModel.h>
-#include <pqServerResource.h>
+//#include <pqServerManagerModel.h>
+//#include <pqServerResource.h>
 #include <pqUndoStack.h>
 #include <pqVCRController.h>
 #include <pqViewManager.h>
+#include <pqPipelineSource.h>
 #include <vtkPVMain.h>
 #include <vtkProcessModule.h>
 
 #include <vtkHybridInstantiator.h>
 #include <vtkParallelInstantiator.h>
 
-#include <vtkPVServerCommonInstantiator.h>
-#include <vtkPVFiltersInstantiator.h>
-#include <vtkPVServerManagerInstantiator.h>
-#include <vtkClientServerInterpreter.h>
+//#include <vtkPVServerCommonInstantiator.h>
+//#include <vtkPVFiltersInstantiator.h>
+//#include <vtkPVServerManagerInstantiator.h>
+//#include <vtkClientServerInterpreter.h>
+
 
 
 //----------------------------------------------------------------------------
@@ -115,31 +138,35 @@ extern "C" void vtkPVServerCommonCS_Initialize(vtkClientServerInterpreter*);
 extern "C" void vtkPVFiltersCS_Initialize(vtkClientServerInterpreter*);
 extern "C" void vtkXdmfCS_Initialize(vtkClientServerInterpreter *);
 
+
 //----------------------------------------------------------------------------
 void ParaViewInitializeInterpreter(vtkProcessModule* pm)
 {
+  vtkClientServerInterpreter* interp = pm->GetInterpreter();
   // Initialize built-in wrapper modules.
-  vtkCommonCS_Initialize(pm->GetInterpreter());
-  vtkFilteringCS_Initialize(pm->GetInterpreter());
-  vtkGenericFilteringCS_Initialize(pm->GetInterpreter());
-  vtkImagingCS_Initialize(pm->GetInterpreter());
-  vtkInfovisCS_Initialize(pm->GetInterpreter());
-  vtkGraphicsCS_Initialize(pm->GetInterpreter());
-  vtkIOCS_Initialize(pm->GetInterpreter());
-  vtkRenderingCS_Initialize(pm->GetInterpreter());
-  vtkVolumeRenderingCS_Initialize(pm->GetInterpreter());
-  vtkHybridCS_Initialize(pm->GetInterpreter());
-  vtkWidgetsCS_Initialize(pm->GetInterpreter());
-  vtkParallelCS_Initialize(pm->GetInterpreter());
-  vtkPVServerCommonCS_Initialize(pm->GetInterpreter());
-  vtkPVFiltersCS_Initialize(pm->GetInterpreter());
-  vtkXdmfCS_Initialize(pm->GetInterpreter());
+  vtkCommonCS_Initialize(interp);
+  vtkFilteringCS_Initialize(interp);
+  vtkGenericFilteringCS_Initialize(interp);
+  vtkImagingCS_Initialize(interp);
+  vtkInfovisCS_Initialize(interp);
+  vtkGraphicsCS_Initialize(interp);
+  vtkIOCS_Initialize(interp);
+  vtkRenderingCS_Initialize(interp);
+  vtkVolumeRenderingCS_Initialize(interp);
+  vtkHybridCS_Initialize(interp);
+  vtkWidgetsCS_Initialize(interp);
+  vtkParallelCS_Initialize(interp);
+  vtkPVServerCommonCS_Initialize(interp);
+  vtkPVFiltersCS_Initialize(interp);
+  vtkXdmfCS_Initialize(interp);
 }
 
 vtkPVMain*                 PVGUI_Module::pqImplementation::myPVMain = 0;
 pqOptions*                 PVGUI_Module::pqImplementation::myPVOptions = 0;
 PVGUI_ProcessModuleHelper* PVGUI_Module::pqImplementation::myPVHelper = 0;
 
+PVGUI_Module* ParavisModule = 0;
+
 /*!
   \mainpage
 
@@ -147,9 +174,8 @@ PVGUI_ProcessModuleHelper* PVGUI_Module::pqImplementation::myPVHelper = 0;
   As any other SALOME module, PARAVIS requires PARAVIS_ROOT_DIR environment variable to be set to PARAVIS
   installation directory.
   Other variables needed for correct detection of ParaView location:
-  \li PVSRCHOME - points at the root of ParaView source directory tree
-  \li PVINSTALLHOME - points at the top of ParaView build tree (currently, due to some drawbacks in its buld procedure
-  ParaView should not be installed, its build directory is used instead).
+  \li PVHOME - points at the ParaView installation directory tree
+  \li PVVERSION - number of ParaView version
 
   It also requires common SALOME environment including GUI_ROOT_DIR and other prerequsites.
 
@@ -158,18 +184,13 @@ PVGUI_ProcessModuleHelper* PVGUI_Module::pqImplementation::myPVHelper = 0;
   mkdir PARAVIS_BUILD
   cd PARAVIS_BUILD
   ../PARAVIS_SRC/build_configure
-  ../PARAVIS_SRC/configure --prefix=${PARAVIS_ROOT_DIR}
+  ../PARAVIS_SRC/configure --prefix=${PARAVIS_ROOT_DIR} -with-paraview
   make 
   make docs
   make install
   \endcode
 
   PARAVIS module can be launched using the following commands:
-  \li Light SALOME configuration
-  \code
-  runLightSalome.sh --modules="PARAVIS"
-  \endcode
-  or
   \li Full SALOME configuration
   \code
   runSalome --modules="PARAVIS"
@@ -258,12 +279,14 @@ PVGUI_ProcessModuleHelper* PVGUI_Module::pqImplementation::myPVHelper = 0;
   \brief Constructor. Sets the default name for the module.
 */
 PVGUI_Module::PVGUI_Module()
-  : LightApp_Module( "PARAVIS" ),
+  : SalomeApp_Module( "PARAVIS" ),
+    LightApp_Module( "PARAVIS" ),
     Implementation( 0 ),
     mySelectionControlsTb( -1 ),
     mySourcesMenuId( -1 ),
     myFiltersMenuId( -1 )
 {
+  ParavisModule = this;
 }
 
 /*!
@@ -279,7 +302,7 @@ PVGUI_Module::~PVGUI_Module()
 */
 void PVGUI_Module::initialize( CAM_Application* app )
 {
-  LightApp_Module::initialize( app );
+  SalomeApp_Module::initialize( app );
 
   // Uncomment to debug ParaView initialization
   // "aa" used instead of "i" as GDB doesn't like "i" variables :)
@@ -295,7 +318,7 @@ void PVGUI_Module::initialize( CAM_Application* app )
 
   // Create GUI elements (menus, toolbars, dock widgets)
   if ( !Implementation ){
-    LightApp_Application* anApp = getApp();
+    SalomeApp_Application* anApp = getApp();
 
     // Simulate ParaView client main window
     Implementation = new pqImplementation( anApp->desktop() );
@@ -310,9 +333,29 @@ void PVGUI_Module::initialize( CAM_Application* app )
 
     // Now that we're ready, initialize everything ...
     Implementation->Core.initializeStates();
+
+    // Force creation of engine
+    PARAVIS::GetParavisGen(this);
+    updateObjBrowser();
   }
+
+  QCoreApplication::processEvents();
+
+  SUIT_ResourceMgr* aResourceMgr = SUIT_Session::session()->resourceMgr();
+  bool isStop = aResourceMgr->booleanValue( "PARAVIS", "stop_trace", false );
+  if(!isStop)
+    QTimer::singleShot(500, this, SLOT(activateTrace()));
+  //  start_trace();
 }
 
+
+void PVGUI_Module::activateTrace()
+{
+  start_trace();
+}
+
+
+
 /*!
   \brief Get list of compliant dockable GUI elements
   \param m map to be filled in ("type":"default_position")
@@ -339,7 +382,7 @@ bool PVGUI_Module::pvInit()
     for ( QStringList::const_iterator it = args.begin(); argc < 1 && it != args.end(); it++, argc++ )
       argv[argc] = strdup( (*it).toLatin1().constData() );
 
-    vtkPVMain::SetInitializeMPI(0);  // pvClient never runs with MPI.
+    vtkPVMain::SetUseMPI(0);  // pvClient never runs with MPI.
     vtkPVMain::Initialize(&argc, &argv); // Perform any initializations.
 
     // TODO: Set plugin dir from preferences
@@ -365,6 +408,8 @@ bool PVGUI_Module::pvInit()
       ret = pqImplementation::myPVHelper->Run(pqImplementation::myPVOptions);
     }
 
+    if (argc == 1)
+      free(argv[0]); // because in creation argc < 1
     delete[] argv;
     return !ret;
   }
@@ -386,7 +431,7 @@ void PVGUI_Module::pvShutdown()
 */
 void PVGUI_Module::showView( bool toShow )
 {
-  LightApp_Application* anApp = getApp();
+  SalomeApp_Application* anApp = getApp();
   PVGUI_ViewManager* viewMgr = dynamic_cast<PVGUI_ViewManager*>( anApp->getViewManager( PVGUI_Viewer::Type(), false ) );
   if ( !viewMgr ) {
     viewMgr = new PVGUI_ViewManager( anApp->activeStudy(), anApp->desktop() );
@@ -502,6 +547,13 @@ void PVGUI_Module::setTimeRanges( double start, double end )
   action(LastFrameId)->setToolTip(QString("Last Frame (%1)").arg(end, 0, 'g'));
 }
 
+
+void PVGUI_Module::connectToPlay()
+{
+  connect( action(PlayId), SIGNAL( triggered() ), &Implementation->Core.VCRController(), SLOT( onPlay() ) );
+}
+
+
 /*!
   \brief Slot to manage the plaing process of animation.
 */
@@ -509,18 +561,16 @@ void PVGUI_Module::onPlaying( bool playing )
 {
   SUIT_ResourceMgr* resMgr = SUIT_Session::session()->resourceMgr();
   if(playing) {
-    disconnect( action(PlayId),                        SIGNAL( triggered() ),
-               &Implementation->Core.VCRController(), SLOT( onPlay() ) );
-    connect( action(PlayId),                        SIGNAL( triggered() ),
-            &Implementation->Core.VCRController(), SLOT( onPause() ) );
+    disconnect( action(PlayId), SIGNAL( triggered() ),&Implementation->Core.VCRController(), SLOT( onPlay() ) );
+    connect( action(PlayId), SIGNAL( triggered() ), &Implementation->Core.VCRController(), SLOT( onPause() ) );
     action(PlayId)->setIcon(QIcon(resMgr->loadPixmap("ParaView",tr("ICON_PAUSE"),false)));
     action(PlayId)->setText("Pa&use");
   }
   else {
-    connect( action(PlayId),                        SIGNAL( triggered() ),
-            &Implementation->Core.VCRController(), SLOT( onPlay() ) );
-    disconnect( action(PlayId),                        SIGNAL( triggered() ),
-               &Implementation->Core.VCRController(), SLOT( onPause() ) );
+    // Immediate connecting toPlay doubles event
+    QTimer::singleShot(10, this, SLOT(connectToPlay()));
+    //connect( action(PlayId), SIGNAL( triggered() ), &Implementation->Core.VCRController(), SLOT( onPlay() ) );
+    disconnect( action(PlayId), SIGNAL( triggered() ), &Implementation->Core.VCRController(), SLOT( onPause() ) );
     action(PlayId)->setIcon(QIcon(resMgr->loadPixmap("ParaView",tr("ICON_PLAY"),false)));
     action(PlayId)->setText("&Play");
   }
@@ -566,13 +616,17 @@ void PVGUI_Module::showHelpForProxy( const QString& proxy )
   // make sure assistant is ready
   this->makeAssistant();
 
-  if(this->Implementation->AssistantClient) {
+  if(this->Implementation->myHelpWindow) {
+    this->Implementation->myHelpWindow->show();
+    this->Implementation->myHelpWindow->raise();
+  }
+  /*  if(this->Implementation->AssistantClient) {
     this->Implementation->AssistantClient->openAssistant();
     QString page("%1/Documentation/%2.html");
     page = page.arg(this->Implementation->DocumentationDir);
     page = page.arg(proxy);
     this->Implementation->AssistantClient->showPage(page);
-  }
+    }*/
 }
 
 QString Locate( const QString& appName )
@@ -605,81 +659,15 @@ QString Locate( const QString& appName )
 */
 void PVGUI_Module::makeAssistant()
 {
-  if(this->Implementation->AssistantClient)
+  if (this->Implementation->myHelpWindow)
     return;
-  
-  QString assistantExe;
-  QString profileFile;
-  
-  const char* assistantName = "assistant";
-#ifdef WNT
-  const char* binDir = "\\";
-  const char* binDir1 = "\\..\\";
-#else
-  const char* binDir = "/";
-  const char* binDir1 = "/bin/";
-#endif
-
-  QString helper = QString(getenv("PVINSTALLHOME")) + binDir + QString("pqClientDocFinder.txt");
-  if(!QFile::exists(helper))
-    helper = QString(getenv("PVINSTALLHOME")) + binDir1 + QString("pqClientDocFinder.txt");
-  if(QFile::exists(helper)) {
-    QFile file(helper);
-    if(file.open(QIODevice::ReadOnly)) {
-      assistantExe = file.readLine().trimmed();
-      profileFile = file.readLine().trimmed();
-      // CMake escapes spaces, we need to unescape those.
-      assistantExe.replace("\\ ", " ");
-      profileFile.replace("\\ ", " ");
-    }
-  }
-
-  if(assistantExe.isEmpty()) {
-    assistantExe = ::Locate(assistantName);//assistantExe = ::Locate(assistantProgName);
-    /*
-    QString assistant = QCoreApplication::applicationDirPath();
-    assistant += QDir::separator();
-    assistant += assistantName;
-    assistantExe = assistant;
-    */
-  }
-
-  this->Implementation->AssistantClient = new QAssistantClient(assistantExe, this);
-  QObject::connect(this->Implementation->AssistantClient, SIGNAL(error(const QString&)),
-                   this,                                  SLOT(assistantError(const QString&)));
-
-  QStringList args;
-  args.append(QString("-profile"));
-
-  if(profileFile.isEmpty()) {
-    // see if help is bundled up with the application
-    QString profile = ::Locate("pqClient.adp");
-    /*QCoreApplication::applicationDirPath() + QDir::separator()
-      + QString("pqClient.adp");*/
-    
-    if(QFile::exists(profile))
-      profileFile = profile;
-  }
-
-  if(profileFile.isEmpty() && getenv("PARAVIEW_HELP")) {
-    // not bundled, ask for help
-    args.append(getenv("PARAVIEW_HELP"));
-  }
-  else if(profileFile.isEmpty()) {
-    // no help, error out
-    SUIT_MessageBox::critical(getApp()->desktop(),"Help error", "Couldn't find"
-                             " pqClient.adp.\nTry setting the PARAVIEW_HELP environment variable which"
-                             " points to that file");
-    delete this->Implementation->AssistantClient;
-    return;
-  }
-
-  QFileInfo fi(profileFile);
-  this->Implementation->DocumentationDir = fi.absolutePath();
 
-  args.append(profileFile);
-
-  this->Implementation->AssistantClient->setArguments(args);
+  pqHelpWindow* helpWindow = new pqHelpWindow("ParaView Online Help", getApp()->desktop());
+  QObject::connect(helpWindow, SIGNAL(helpWarnings(const QString&)),
+                   this, SLOT(assistantError(const QString&)));
+  helpWindow->registerDocumentation(":/ParaViewResources/pqClient.qch");
+  this->Implementation->myHelpWindow = helpWindow;
+  this->Implementation->myHelpWindow->showPage("qthelp://paraview.org/paraview/Documentation/index.html");
 }
 
 /*!
@@ -774,7 +762,7 @@ bool PVGUI_Module::eventFilter( QObject* theObject, QEvent* theEvent )
 */
 bool PVGUI_Module::activateModule( SUIT_Study* study )
 {
-  bool isDone = LightApp_Module::activateModule( study );
+  bool isDone = SalomeApp_Module::activateModule( study );
   if ( !isDone ) return false;
 
   showView( true );
@@ -816,7 +804,7 @@ bool PVGUI_Module::deactivateModule( SUIT_Study* study )
 
   saveDockWidgetsState();
 
-  return LightApp_Module::deactivateModule( study );
+  return SalomeApp_Module::deactivateModule( study );
 }
 
 /*!
@@ -829,8 +817,11 @@ bool PVGUI_Module::deactivateModule( SUIT_Study* study )
 */
 void PVGUI_Module::onApplicationClosed( SUIT_Application* theApp )
 {
-  pvShutdown();
-  
+  int aAppsNb = SUIT_Session::session()->applications().size();
+  if (aAppsNb == 1) {
+    deleteTemporaryFiles();
+    pvShutdown();
+  }
   CAM_Module::onApplicationClosed(theApp);
 }
 
@@ -839,13 +830,162 @@ void PVGUI_Module::onApplicationClosed( SUIT_Application* theApp )
   returns true if they "match" within some tolerance.
 */
 bool PVGUI_Module::compareView( const QString& ReferenceImage, double Threshold,
-                               ostream& Output, const QString& TempDirectory )
+                                std::ostream& Output, const QString& TempDirectory )
 {
   if ( Implementation )
     return Implementation->Core.compareView( ReferenceImage, Threshold, Output, TempDirectory );
   return false;
 }
 
+QString PVGUI_Module::engineIOR() const
+{
+  CORBA::String_var anIOR = PARAVIS::GetParavisGen(this)->GetIOR();
+  return QString(anIOR.in());
+}
+
+void PVGUI_Module::onOpenFile()
+{
+  // This avoids an immediate exception on wrong MED file opening
+  Implementation->Core.onFileOpen();
+}
+
+/*!
+  \brief Open file of format supported by ParaView
+*/
+void PVGUI_Module::openFile(const char* theName)
+{
+  QStringList aFiles;
+  aFiles<<theName;
+  Implementation->Core.createReaderOnActiveServer(aFiles);
+}
+
+/*!
+  \brief Returns trace string
+*/
+QString PVGUI_Module::printTrace()
+{
+  return get_trace_string();
+}
+
+/*!
+  \brief Saves trace string to disk file
+*/
+void PVGUI_Module::saveTrace(const char* theName)
+{
+  save_trace(theName);
+}
+
+/*!
+  \brief Saves ParaView state to a disk file
+*/
+void PVGUI_Module::saveParaviewState(const char* theFileName)
+{
+  QStringList aFiles;
+  aFiles<<theFileName;
+  Implementation->Core.onFileSaveServerState(aFiles);
+}
+
+/*!
+  \brief Restores ParaView state from a disk file
+*/
+void PVGUI_Module::loadParaviewState(const char* theFileName)
+{
+  QStringList aFiles;
+  aFiles<<theFileName;
+  Implementation->Core.onFileLoadServerState(aFiles);
+}
+
+/*!
+  \brief Imports MED data from VISU module by data entry
+*/
+void PVGUI_Module::onImportFromVisu(QString theEntry)
+{
+  SUIT_OverrideCursor aWaitCursor;
+
+  // get active study
+  SalomeApp_Study* activeStudy = dynamic_cast<SalomeApp_Study*>(application()->activeStudy());
+  if(!activeStudy) return;
+
+  // get SALOMEDS client study 
+  _PTR(Study) aStudy = activeStudy->studyDS();
+  if(!aStudy) return;
+
+  // find VISU component in a study
+  _PTR(SComponent) aVisuComp = aStudy->FindComponent( "VISU" );
+  if(!aVisuComp) return;
+
+  // get SObject client by entry
+  _PTR(SObject) aSObj = aStudy->FindObjectID(qPrintable(theEntry));
+  if (!aSObj) return;
+
+  // get CORBA SObject
+  SALOMEDS_SObject* aSObject = _CAST(SObject, aSObj);
+  if ( !aSObject ) return;
+
+  // load VISU engine
+  SALOME_NamingService* aNamingService = SalomeApp_Application::namingService();
+  SALOME_LifeCycleCORBA aLCC(aNamingService);
+
+  Engines::Component_var aComponent = aLCC.FindOrLoad_Component("FactoryServer","VISU");
+  VISU::VISU_Gen_var aVISU = VISU::VISU_Gen::_narrow(aComponent);
+  if(CORBA::is_nil(aVISU)) return;
+
+  _PTR(StudyBuilder) aStudyBuilder = aStudy->NewBuilder();
+  aStudyBuilder->LoadWith( aVisuComp, SalomeApp_Application::orb()->object_to_string(aVISU) );
+
+  // set current study to VISU engine
+  //aVISU->SetCurrentStudy(aStudyVar);
+
+  // get VISU result object
+  CORBA::Object_var aResultObject = aSObject->GetObject();
+  if (CORBA::is_nil(aResultObject)) return;
+  VISU::Result_var aResult = VISU::Result::_narrow( aResultObject );
+  if (CORBA::is_nil(aResult)) return;
+
+  // export VISU result to the MED file
+  std::string aTmpDir = SALOMEDS_Tool::GetTmpDir();
+  std::string aFileName = aSObject->GetName();
+  std::string aFilePath = aTmpDir + aFileName;
+
+  if (aResult->ExportMED(aFilePath.c_str())) {
+    openFile(aFilePath.c_str());
+    myTemporaryFiles.append(QString(aFilePath.c_str()));
+  }
+}
+
+/*!
+  \brief Deletes temporary files created during import operation from VISU
+*/
+void PVGUI_Module::deleteTemporaryFiles()
+{
+  foreach(QString aFile, myTemporaryFiles) {
+    if (QFile::exists(aFile)) {
+      QFile::remove(aFile);
+    }
+  }
+}
+
+
+/*!
+  \brief Returns current active ParaView server
+*/
+pqServer* PVGUI_Module::getActiveServer()
+{
+  return Implementation->Core.getActiveServer();
+}
+
+
+/*!
+  \brief Creates PARAVIS preference pane 
+*/
+void PVGUI_Module::createPreferences()
+{
+  int TraceTab = addPreference( tr( "TIT_TRACE" ) );
+  addPreference( tr( "PREF_STOP_TRACE" ), TraceTab, LightApp_Preferences::Bool, "PARAVIS", "stop_trace");
+}
+
+
+
 /*!
   \fn CAM_Module* createModule();
   \brief Export module instance (factory function).
index 0945423721b0cb8fc78c3b6f91e64d089507632c..f586e07cf661500161f2755394f5ec4df4dbb42f 100644 (file)
 #ifndef PVGUI_Module_H
 #define PVGUI_Module_H
 
-#include <LightApp_Module.h>
+#include <SalomeApp_Module.h>
 
-#include <ostream.h>
+#include <ostream>
 
 class QMenu;
 class QDockWidget;
-class LightApp_Selection;
-class LightApp_SelectionMgr;
+//class LightApp_Selection;
+//class LightApp_SelectionMgr;
 class PVGUI_ProcessModuleHelper;
 class vtkPVMain;
 class pqOptions;
 class pqServer;
-class pqActiveServer;
 class pqViewManager;
+class pqMainWindowCore;
 
-class PVGUI_Module : public LightApp_Module
+class PVGUI_Module : public SalomeApp_Module
 {
   Q_OBJECT
    
@@ -157,9 +157,25 @@ public:
 
   virtual bool           eventFilter( QObject*, QEvent* );
 
+  virtual QString engineIOR() const;
+
   //! Compares the contents of the window with the given reference image, returns true if they "match" within some tolerance
   bool                   compareView( const QString& ReferenceImage, double Threshold,
-                                     ostream& Output, const QString& TempDirectory );
+                                      std::ostream& Output, const QString& TempDirectory );
+
+  void openFile(const char* theName);
+  void saveParaviewState(const char* theFileName);
+  void loadParaviewState(const char* theFileName);
+
+  QString printTrace();
+  void saveTrace(const char* theName);
+
+  pqServer* getActiveServer();
+
+  virtual void createPreferences();
+
+public slots:
+  void onImportFromVisu(QString theEntry);
 
 protected:
   //virtual CAM_DataModel* createDataModel();
@@ -197,6 +213,8 @@ private:
   //! Returns QMenu object for a given menu id
   QMenu*                 getMenu( const int );
 
+  void                   deleteTemporaryFiles();
+
 private slots:
   void onUndoLabel( const QString& );
   void onRedoLabel( const QString& );
@@ -228,6 +246,12 @@ private slots:
   void onPostAccept();
   void endWaitCursor();
 
+  void connectToPlay();
+
+  void onOpenFile();
+
+  void activateTrace();
+
 public slots:
   virtual bool           activateModule( SUIT_Study* );
   virtual bool           deactivateModule( SUIT_Study* );
@@ -242,6 +266,8 @@ private:
   int                    myFiltersMenuId;
 
   QList<QDockWidget*>    myDockWidgets;
+
+  QStringList            myTemporaryFiles;
 };
 
 #endif // PVGUI_Module_H
index 38d55b4ffac375bde83c40deaf72d735f6113966..78a3aea1bbf554311ba11b12f75428cf3a0724cd 100644 (file)
@@ -31,7 +31,7 @@
 #include <SUIT_Desktop.h>
 #include <SUIT_ResourceMgr.h>
 #include <SUIT_Session.h>
-#include <LightApp_Application.h>
+#include <SalomeApp_Application.h>
 
 #include <QAction>
 #include <QMenu>
@@ -48,6 +48,9 @@
 #include <pqUndoStack.h>
 #include <pqVCRController.h>
 
+#include "PVGUI_Tools.h"
+
+
 /*!
   \brief Create actions for ParaView GUI operations
   duplicating menus and toolbars in MainWindow class of
@@ -68,7 +71,9 @@ void PVGUI_Module::pvCreateActions()
   aPixmap = resMgr->loadPixmap( "ParaView", tr("ICON_OPEN_FILE"), false );
   createAction( OpenFileId, tr("TOP_OPEN_FILE"), QIcon(aPixmap),
                 tr("MEN_OPEN"), tr("STB_OPEN_FILE"), 
-               0, desk, false, &Implementation->Core, SLOT( onFileOpen() ) );
+   //0, desk, false, &Implementation->Core, SLOT( onFileOpen() ) );
+  // This avoids an immediate exception on wrong MED file opening
+               0, desk, false, this, SLOT( onOpenFile() ) );
 
   // Load State
   anAction = createAction( LoadStateId, tr("TOP_LOAD_STATE"), QIcon(),
@@ -857,7 +862,7 @@ void PVGUI_Module::pvCreateToolBars()
 QMenu* PVGUI_Module::getMenu( const int id )
 {
   QMenu* res = 0;
-  LightApp_Application* anApp = getApp();
+  SalomeApp_Application* anApp = getApp();
   SUIT_Desktop* desk = anApp->desktop();
   if ( desk ){
     QtxActionMenuMgr* menuMgr = desk->menuMgr();
index 55a01629b885c723555907a6edced0445b8bd67a..054f6f2fa74fe7dc693e074042c83691d9206019 100644 (file)
@@ -28,7 +28,8 @@
 
 #include "PVGUI_Module.h"
 
-#include <QAssistantClient>
+//#include <QAssistantClient>
+#include <pqHelpWindow.h>
 #include <QPointer>
 
 #include <pqMainWindowCore.h>
@@ -41,7 +42,8 @@ class PVGUI_Module::pqImplementation
 {
  public:
   pqImplementation(QWidget* parent) :
-    AssistantClient(0),
+    //AssistantClient(0),
+    myHelpWindow(0),
     Core(parent),
     RecentFilesMenu(0)
   {
@@ -49,17 +51,16 @@ class PVGUI_Module::pqImplementation
   
   ~pqImplementation()
   {
-    if(this->AssistantClient) {
-      this->AssistantClient->closeAssistant();
-      delete this->AssistantClient;
-    }
+    if (myHelpWindow)
+      delete myHelpWindow;
   }
   
-  QPointer<QAssistantClient> AssistantClient;
+  //QPointer<QAssistantClient> AssistantClient;
   pqMainWindowCore Core;
   pqRecentFilesMenu* RecentFilesMenu;
-  QPointer<pqServer> ActiveServer;
+  //QPointer<pqServer> ActiveServer;
   QString DocumentationDir;
+  QPointer<pqHelpWindow> myHelpWindow;
   
   static vtkPVMain* myPVMain;
   static pqOptions* myPVOptions;
index 28f122ca7ccac9813fc9e66dc67e5ae55b954d32..edcf1bb61a5db8b7c65db19fcd3c5c37acc83da7 100644 (file)
@@ -33,7 +33,9 @@
 #include <QDockWidget>
 #include <QToolBar>
 
-#include <pqAnimationPanel.h>
+//VSV #include <pqAnimationPanel.h>
+#include <pqAnimationViewWidget.h> //VSV
+
 #include <pqApplicationCore.h>
 #include <pqComparativeVisPanel.h>
 #include <pqMainWindowCore.h>
@@ -85,11 +87,12 @@ void PVGUI_Module::setupDockWidgets()
   QDockWidget* animationPanelDock  = new QDockWidget( tr( "TTL_ANIMATION_INSPECTOR" ), desk );
   animationPanelDock->setObjectName("animationPanelDock");
   desk->addDockWidget( Qt::LeftDockWidgetArea, animationPanelDock );
-  pqAnimationPanel* animation_panel = Implementation->Core.setupAnimationPanel( animationPanelDock );
+  //pqAnimationPanel* animation_panel = Implementation->Core.setupAnimationPanel( animationPanelDock );
+  pqAnimationViewWidget* animation_panel = Implementation->Core.setupAnimationView( animationPanelDock );
   
   int aToolId = createTool( tr("TOOL_CURRENT_TIME_CONTROLS") );
   QToolBar* aTB = toolMgr()->toolBar( aToolId );
-  animation_panel->setCurrentTimeToolbar( aTB );
+  //animation_panel->setCurrentTimeToolbar( aTB );
   QList<QAction*> anActns = aTB->actions();
   for (int i = 0; i < anActns.size(); ++i)
     createTool( anActns.at(i), aToolId );
@@ -166,13 +169,13 @@ void PVGUI_Module::setupDockWidgetsContextMenu()
   pqPipelineBrowser *browser = Implementation->Core.pipelineBrowser();
   pqPipelineBrowserContextMenu *browserMenu = new pqPipelineBrowserContextMenu(browser);
 
-  browserMenu->setMenuAction(action(OpenFileId));
+  browserMenu->setMenuAction(pqPipelineBrowserContextMenu::OPEN, action(OpenFileId));
   if ( action(OpenFileId)->text().compare(tr("MEN_OPEN")) == 0 )
     action(OpenFileId)->setText(tr("MEN_OPEN_FILE"));
 
-  browserMenu->setMenuAction(action(ChangeInputId));
-  browserMenu->setMenuAction(action(DeleteId));
-  browserMenu->setMenuAction(action(CreateCustomFilterId));
+  browserMenu->setMenuAction(pqPipelineBrowserContextMenu::CHANGE_INPUT, action(ChangeInputId));
+  browserMenu->setMenuAction(pqPipelineBrowserContextMenu::DELETE, action(DeleteId));
+  browserMenu->setMenuAction(pqPipelineBrowserContextMenu::CREATE_CUSTOM_FILTER, action(CreateCustomFilterId));
 }
 
 /*!
diff --git a/src/PVGUI/PVGUI_Tools.cxx b/src/PVGUI/PVGUI_Tools.cxx
new file mode 100644 (file)
index 0000000..fb292ee
--- /dev/null
@@ -0,0 +1,58 @@
+//  Copyright (C) 2007-2008  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.
+//
+//  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
+//
+//  VISU VISUGUI : GUI of VISU component
+//  File   : PVGUI_Tools.cxx
+//  Author : Vitaly Smetannikov
+//  Module : PARAVIS
+//
+
+#include "PVGUI_Tools.h"
+#include "CAM_Module.h"
+#include "SALOME_LifeCycleCORBA.hxx"
+#include "SalomeApp_Application.h"
+#include <stdexcept>
+
+using namespace std;
+
+//=============================================================================
+namespace PARAVIS
+{
+  //------------------------------------------------------------
+  PARAVIS_Gen_i* GetParavisGen(const CAM_Module* theModule)
+  {
+    static PARAVIS_Gen_i* aGen = NULL;
+    if(!aGen){
+      SALOME_LifeCycleCORBA aLCC(SalomeApp_Application::namingService());
+      Engines::Component_var aComponent = aLCC.FindOrLoad_Component("FactoryServer","PARAVIS");
+      PARAVIS_Gen_var aPARAVIS = PARAVIS_Gen::_narrow(aComponent);
+      if(!CORBA::is_nil(aPARAVIS)){
+        aGen = PARAVIS_Gen_i::GetParavisGenImpl();
+        //if(aGen)
+        //aGen->SetCurrentStudy(GetDSStudy(GetCStudy(GetAppStudy(theModule))));
+      }
+    }
+    if(!aGen)
+      throw std::runtime_error("Can not create PARAVIS_Gen");
+    return aGen;
+  }
+
+}
diff --git a/src/PVGUI/PVGUI_Tools.h b/src/PVGUI/PVGUI_Tools.h
new file mode 100644 (file)
index 0000000..7b929c8
--- /dev/null
@@ -0,0 +1,40 @@
+// PARAVIS : ParaView wrapper SALOME module
+//
+// Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
+// CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License.
+//
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
+//
+// See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
+//
+// File   : PVGUI_Tools.h
+// Author : Vitaly Smetannikov
+//
+
+#ifndef PVGUI_Tools_H
+#define PVGUI_Tools_H
+
+#include "PARAVIS_Gen_i.hh"
+
+class CAM_Module;
+
+namespace PARAVIS 
+{
+  
+  PARAVIS_Gen_i* GetParavisGen(const CAM_Module* theModule);
+
+};
+
+#endif // PVGUI_Tools_H
diff --git a/src/PVGUI/PVGUI_Trace.cxx b/src/PVGUI/PVGUI_Trace.cxx
new file mode 100644 (file)
index 0000000..a148f73
--- /dev/null
@@ -0,0 +1,857 @@
+#include "PVGUI_Trace.h"
+#include "PVGUI_Module.h"
+
+#include <vtkSMPythonTraceObserver.h>
+#include <vtkSMSourceProxy.h>
+#include <vtkSMViewProxy.h>
+#include <vtkSMProxy.h>
+#include <vtkSMProperty.h>
+#include <vtkSMProxyProperty.h>
+#include <vtkSMProxyIterator.h>
+#include <pqServer.h>
+#include <vtkSMProxyManager.h>
+#include <vtkSMDomain.h>
+#include <vtkSMProxyListDomain.h>
+#include <vtkSMProxyGroupDomain.h>
+#include <vtkSMPropertyIterator.h>
+#include <vtkCallbackCommand.h>
+#include <vtkSMStringVectorProperty.h>
+#include <vtkSMIntVectorProperty.h>
+#include <vtkSMIdTypeVectorProperty.h>
+#include <vtkSMDoubleVectorProperty.h>
+#include <vtkSMEnumerationDomain.h>
+#include <vtkSMDomainIterator.h>
+#include <vtkSMInputProperty.h>
+
+#include <QFile>
+#include <QTextStream>
+
+extern PVGUI_Module* ParavisModule;
+
+static trace_globals globals;
+static bool myInitialised = false;
+
+
+//********************************************************************
+QString pyvariable_from_proxy_name(const QString& proxy_name)
+{
+  QString aName = proxy_name;
+  return make_name_valid(aName.replace(".", "_"));
+}
+
+//********************************************************************
+proxy_trace_info::proxy_trace_info(vtkSMProxy* proxy, 
+                                   const QString& proxyGroup, 
+                                   const QString& proxyName) 
+{
+  Proxy = proxy;
+  Group = proxyGroup;
+  ProxyName = proxyName;
+  PyVariable = pyvariable_from_proxy_name(proxyName);
+  ignore_next_unregister = false;
+}
+  
+//********************************************************************
+prop_trace_info::prop_trace_info(const proxy_trace_info_ptr proxyTraceInfo, vtkSMProperty* prop) 
+{
+  Prop = prop;
+  // Determine python variable name
+  PyVariable = prop->GetXMLLabel();
+  // For non-self properties, use the xml name instead of xml label:
+  if (prop->GetParent() != proxyTraceInfo->Proxy)
+    PyVariable = proxyTraceInfo->Proxy->GetPropertyName(prop);
+  PyVariable = make_name_valid(PyVariable);
+}
+
+
+//********************************************************************
+QString make_name_valid(const QString& theName)
+{
+  QString name = theName;
+  if (name.isNull())
+    return QString("");
+  if ((name.indexOf('(') >= 0) || (name.indexOf(')') >=0))
+    return QString("");
+  name = name.replace(" ","");
+  name = name.replace("-","");
+  name = name.replace(":","");
+  name = name.replace(".","");
+  if (!name.at(0).isLetter())
+    name = "a" + name;
+  return name;
+}
+
+//********************************************************************
+vtkSMPythonTraceObserver* trace_observer()
+{
+  return globals.observer;
+}
+
+//********************************************************************
+QStringList ignoredViewProperties()
+{
+  return globals.ignored_view_properties;
+}
+
+//********************************************************************
+QStringList ignoredRepresentationProperties()
+{
+  return globals.ignored_representation_properties;
+}
+
+//********************************************************************
+bool propIsIgnored(const proxy_trace_info_ptr info, const QString& propName)
+{
+  QStringList aIgnoredList = ignoredViewProperties();
+  if ((info->Group == "views") && (aIgnoredList.contains(propName))) 
+    return true;
+  aIgnoredList = ignoredRepresentationProperties();
+  if ((info->Group == "representations") && (aIgnoredList.contains(propName)))
+    return true;
+  return false;
+}
+
+//********************************************************************
+bool operator < (const QStringList& list1, const QStringList& list2) {
+  QString s1 = list1.join(":");
+  QString s2 = list2.join(":");
+  return (s1 < s2);
+}
+
+//********************************************************************
+void GetProxiesInGroup(const char* theName, QMap<QStringList,vtkSMProxy*>& proxies) 
+{
+  pqServer* aServer = ParavisModule->getActiveServer();
+
+  vtkSMProxyIterator* aIt = vtkSMProxyIterator::New();
+  aIt->SetConnectionID(aServer->GetConnectionID());
+  aIt->SetModeToOneGroup();
+  for (aIt->Begin(theName); !aIt->IsAtEnd(); aIt->Next()) {
+    vtkSMProxy* aProxy = aIt->GetProxy();
+    QStringList aKey;
+    aKey << aIt->GetKey() << aProxy->GetSelfIDAsString();
+    proxies[aKey] = aProxy;
+  }
+  aIt->Delete();
+}
+
+//********************************************************************
+void track_existing_sources()
+{
+  QMap<QStringList, vtkSMProxy*> existing_sources;
+  GetProxiesInGroup("sources", existing_sources);
+
+  QMap<QStringList, vtkSMProxy*>::const_iterator aIt;
+  for (aIt = existing_sources.constBegin(); aIt!=existing_sources.constEnd(); ++aIt) {
+    QStringList aKey = aIt.key();
+    vtkSMProxy* aProxy = aIt.value();
+    track_existing_source_proxy(aProxy, "");
+  }
+}
+
+//********************************************************************
+proxy_trace_info_ptr track_existing_source_proxy(vtkSMProxy* proxy, const QString& proxy_name)
+{
+  proxy_trace_info_ptr proxy_info(new proxy_trace_info(proxy, "sources", proxy_name));
+  globals.registered_proxies.append(proxy_info);
+  if ((!globals.last_active_source) && (proxy == globals.active_source_at_start)) {
+    globals.last_active_source = proxy;
+    globals.trace_output.append(QString("%1 = GetActiveSource()").arg(proxy_info->PyVariable));
+  } else {
+    globals.trace_output.append(QString("%1 = FindSource(\"%2\")").arg(proxy_info->PyVariable).arg(proxy_name));
+  }
+  return proxy_info;
+}
+
+//********************************************************************
+QList<vtkSMProxy*> GetRenderViews() 
+{
+  QList<vtkSMProxy*> render_modules;
+
+  pqServer* aServer = ParavisModule->getActiveServer();
+
+  vtkSMProxyIterator* aIt = vtkSMProxyIterator::New();
+  aIt->SetConnectionID(aServer->GetConnectionID());
+  for (aIt->Begin(); !aIt->IsAtEnd(); aIt->Next()) {
+    vtkSMProxy* aProxy = aIt->GetProxy();
+    if (aProxy->IsA("vtkSMRenderViewProxy"))
+      render_modules.append(aProxy);
+  }
+  aIt->Delete();
+  return render_modules;
+}
+
+//********************************************************************
+proxy_trace_info_ptr track_existing_view_proxy(vtkSMProxy* proxy, const QString& proxy_name)
+{
+  proxy_trace_info_ptr proxy_info(new proxy_trace_info(proxy, "views", proxy_name));
+  globals.registered_proxies.append(proxy_info);
+  if ((!globals.last_active_view) && (proxy == globals.active_view_at_start)) {
+    globals.last_active_view = proxy;
+    globals.trace_output.append(QString("%1 = GetRenderView()").arg(proxy_info->PyVariable));
+  } else {
+    QList<vtkSMProxy*> all_views = GetRenderViews();
+    if (all_views.contains(proxy)) {
+      int view_index = all_views.indexOf(proxy);
+      if (view_index != -1)
+        globals.trace_output.append(QString("%1 = GetRenderViews()[%2]").arg(proxy_info->PyVariable).arg(view_index));
+    }
+  }
+  return proxy_info;
+}
+
+//********************************************************************
+proxy_trace_info_ptr track_existing_representation_proxy(vtkSMProxy* proxy, 
+                                                         const QString& proxy_name)
+{
+  vtkSMProxyProperty* input_property = dynamic_cast<vtkSMProxyProperty*>(proxy->GetProperty("Input"));
+  if (!input_property) return proxy_trace_info_ptr();
+  
+  if (input_property->GetNumberOfProxies() > 0) {
+    vtkSMProxy* input_proxy = input_property->GetProxy(0);
+    proxy_trace_info_ptr input_proxy_info = get_proxy_info(input_proxy);
+    if (input_proxy_info.get()) {
+      proxy_trace_info_ptr proxy_info(new proxy_trace_info(proxy, "representations", proxy_name));
+      globals.registered_proxies.append(proxy_info);
+      globals.trace_output.append(QString("%1 = GetDisplayProperties(%2)").arg(proxy_info->PyVariable).arg(input_proxy_info->PyVariable));
+      return proxy_info;
+    }
+  }
+  return proxy_trace_info_ptr();
+}
+
+//********************************************************************
+proxy_trace_info_ptr track_existing_proxy(vtkSMProxy* proxy)
+{
+  QString proxy_name = get_source_proxy_registration_name(proxy);
+  if (!proxy_name.isNull())
+    return track_existing_source_proxy(proxy, proxy_name);
+
+  proxy_name = get_representation_proxy_registration_name(proxy);
+  if (!proxy_name.isNull())
+    return track_existing_representation_proxy(proxy, proxy_name);
+
+  proxy_name = get_view_proxy_registration_name(proxy);
+  if (!proxy_name.isNull())
+    return track_existing_view_proxy(proxy, proxy_name);
+  return proxy_trace_info_ptr();
+}
+
+//********************************************************************
+proxy_trace_info_ptr get_proxy_info(const QString& p, bool search_existing)
+{
+  foreach(proxy_trace_info_ptr info, globals.last_registered_proxies) {
+    if (info->PyVariable == p) return info;
+  }
+  foreach(proxy_trace_info_ptr info, globals.registered_proxies) {
+    if (info->PyVariable == p) return info;
+  }
+
+  if(search_existing) return proxy_trace_info_ptr();
+
+  return proxy_trace_info_ptr();
+}
+
+//********************************************************************
+proxy_trace_info_ptr get_proxy_info(vtkSMProxy* p, bool search_existing)
+{
+  foreach(proxy_trace_info_ptr info, globals.last_registered_proxies) {
+    if (info->Proxy == p) return info;
+  }
+  foreach(proxy_trace_info_ptr info, globals.registered_proxies) {
+    if (info->Proxy == p) return info;
+  }
+  // It must be a proxy that existed before trace started
+  if (search_existing) return track_existing_proxy(p);
+
+  return proxy_trace_info_ptr();
+}
+
+//********************************************************************
+void ensure_active_source(const proxy_trace_info_ptr proxy_info)
+{
+  if (proxy_info && (proxy_info->Proxy != globals.last_active_source)) {
+    globals.trace_output.append(QString("SetActiveSource(%1)").arg(proxy_info->PyVariable));
+    globals.last_active_source = proxy_info->Proxy;
+  }
+}
+
+//********************************************************************
+void ensure_active_view(const proxy_trace_info_ptr proxy_info)
+{
+  if (proxy_info && (proxy_info->Proxy != globals.last_active_view)) {
+    globals.trace_output.append(QString("SetActiveView(%1)").arg(proxy_info->PyVariable));
+    globals.last_active_view = proxy_info->Proxy;
+  }
+}
+
+//********************************************************************
+proxy_trace_info_ptr get_input_proxy_info_for_rep(const proxy_trace_info_ptr rep_info)
+{
+  if (rep_info->CurrentProps.contains("Input")) {
+    QString input_proxy_pyvariable = rep_info->CurrentProps["Input"];
+    return get_proxy_info(input_proxy_pyvariable);
+  }
+  return proxy_trace_info_ptr();
+}
+//********************************************************************
+proxy_trace_info_ptr get_view_proxy_info_for_rep(const proxy_trace_info_ptr rep_info)
+{
+  QList<proxy_trace_info_ptr> aTmpList;
+  aTmpList.append(globals.registered_proxies);
+  aTmpList.append(globals.last_registered_proxies);
+  foreach (proxy_trace_info_ptr p, aTmpList) {
+    // If the proxy is a view, check for rep_info.Proxy in the
+    // view's 'Representation' property
+    if (p->Group == "views") {
+      vtkSMProxyProperty* rep_prop = 
+        dynamic_cast<vtkSMProxyProperty*>(p->Proxy->GetProperty("Representations"));
+      if (rep_prop) {
+        for (int i = 0; i < rep_prop->GetNumberOfProxies(); i++) {
+          if (rep_info->Proxy == rep_prop->GetProxy(i)) 
+            return p;
+        }
+      }
+    }
+  }
+  return proxy_trace_info_ptr();
+}
+
+//********************************************************************
+QString get_source_proxy_registration_name(vtkSMProxy* proxy)
+{
+  return vtkSMObject::GetProxyManager()->GetProxyName("sources", proxy);
+}
+
+//********************************************************************
+QString get_view_proxy_registration_name(vtkSMProxy* proxy)
+{
+  return vtkSMObject::GetProxyManager()->GetProxyName("views", proxy);
+}
+
+//********************************************************************
+QString get_representation_proxy_registration_name(vtkSMProxy* proxy)
+{
+  return vtkSMObject::GetProxyManager()->GetProxyName("representations", proxy);
+}
+
+//********************************************************************
+QString make_comma_separated_string(QStringList values)
+{
+  QString ret=values.join(", ");
+  if(ret!="")
+    ret = QString(" %1 ").arg(ret);
+  return ret;
+}
+
+QStringList wrap_property(vtkSMProxy* proxy, vtkSMProperty* smproperty)
+{
+  QStringList propertyList;
+  if(smproperty->IsA("vtkSMVectorProperty")) {
+    vtkSMVectorProperty* property = dynamic_cast<vtkSMVectorProperty*>(smproperty);
+    int nElem = property->GetNumberOfElements();
+    int di = 1;
+    vtkSMDomain* dom = NULL;
+    if(property->IsA("vtkSMStringVectorProperty")) {
+      dom = property->GetDomain("array_list");
+      if(dom!=NULL && dom->IsA("vtkSMArraySelectionDomain") && property->GetRepeatable()) {
+       if(nElem%2 != 0) {
+         cerr << "!!!Error: The SMProperty with XML label" << smproperty->GetXMLLabel() << "has a size that is not a multiple of 2." << endl;
+         nElem=0;
+       } else {
+         di=2;
+       }
+      }
+    } else if(property->IsA("vtkSMIntVectorProperty")) {
+      dom = property->GetDomain("enum");
+    }
+    for(int i = 0; i < nElem; i+=di) {
+      bool ap=true;
+      if(di!=1) {
+       if(dynamic_cast<vtkSMStringVectorProperty*>(property)->GetElement(i+1) == "0") {
+         ap=false;
+       }
+      }
+      if(ap) {
+       if(property->IsA("vtkSMStringVectorProperty"))
+         propertyList.append(QString("'%1'").arg(dynamic_cast<vtkSMStringVectorProperty*>(property)->GetElement(i)));
+       if(property->IsA("vtkSMIntVectorProperty")) {
+         if(dom == NULL) {
+           propertyList.append(QString("%1").arg(dynamic_cast<vtkSMIntVectorProperty*>(property)->GetElement(i)));
+         } else {
+           for(int j = 0; j < dynamic_cast<vtkSMEnumerationDomain*>(dom)->GetNumberOfEntries(); j++) {
+             if(dynamic_cast<vtkSMEnumerationDomain*>(dom)->GetEntryValue(j) == dynamic_cast<vtkSMIntVectorProperty*>(property)->GetElement(i)) {
+               propertyList.append(QString("'%1'").arg(dynamic_cast<vtkSMEnumerationDomain*>(dom)->GetEntryText(j)));
+               break;
+             }
+           }
+         }
+       }
+       if(property->IsA("vtkSMIdTypeVectorProperty"))
+         propertyList.append(QString("%1").arg(dynamic_cast<vtkSMIdTypeVectorProperty*>(property)->GetElement(i)));
+       if(property->IsA("vtkSMDoubleVectorProperty"))
+         propertyList.append(QString("%1").arg(dynamic_cast<vtkSMDoubleVectorProperty*>(property)->GetElement(i)));
+      }
+    }
+  }
+  return propertyList;
+}
+
+//********************************************************************
+QString vector_smproperty_tostring(const proxy_trace_info_ptr proxyInfo, 
+                                   const prop_trace_info_ptr propInfo)
+{
+  vtkSMProxy* proxy = proxyInfo->Proxy;
+  vtkSMProperty* prop = propInfo->Prop;
+  QStringList propList = wrap_property(proxy, prop);
+  QString pythonProp;
+  if (propList.size() == 0) 
+    pythonProp = "[]";
+  if (propList.size() == 1) 
+    return propList.first();
+  if (propList.size() > 1) {
+    pythonProp = make_comma_separated_string(propList);
+    pythonProp = QString("[%1]").arg(pythonProp);
+  }
+  return pythonProp;
+}
+
+//********************************************************************
+QString get_property_value_from_list_domain(const proxy_trace_info_ptr proxyInfo, 
+                                            const prop_trace_info_ptr propInfo)
+{
+  vtkSMProxy* proxy = proxyInfo->Proxy;
+  vtkSMProxyProperty* prop = dynamic_cast<vtkSMProxyProperty*>(propInfo->Prop);
+  vtkSMProxyListDomain* listdomain = dynamic_cast<vtkSMProxyListDomain*>(prop->GetDomain("proxy_list"));
+  if (listdomain != NULL && prop->GetNumberOfProxies() == 1) {
+    vtkSMProxy* proxyPropertyValue = prop->GetProxy(0);   
+    for (int i = 0; i < listdomain->GetNumberOfProxies(); i++) {
+      if (listdomain->GetProxy(i) == proxyPropertyValue) {
+       proxy_trace_info_ptr info = get_proxy_info(proxyPropertyValue);
+       if (!info) {
+         proxy_trace_info_ptr infotmp(new proxy_trace_info(proxyPropertyValue, "helpers", listdomain->GetProxy(i)->GetXMLLabel()));
+         info = infotmp;
+       }
+       info->PyVariable = QString("%1.%2").arg(proxyInfo->PyVariable).arg(propInfo->PyVariable);
+       globals.registered_proxies.append(info);
+       return QString("\"%1\"").arg(listdomain->GetProxy(i)->GetXMLLabel());
+      }
+    }
+  }
+  return QString();
+}
+
+//********************************************************************
+QString proxy_smproperty_tostring(const proxy_trace_info_ptr proxyInfo, 
+                                  const prop_trace_info_ptr propInfo)
+{
+  QString strValue = get_property_value_from_list_domain(proxyInfo, propInfo);
+  if (!strValue.isNull()) 
+    return strValue;
+  vtkSMProxy* proxy = proxyInfo->Proxy;
+  vtkSMProxyProperty* prop = dynamic_cast<vtkSMProxyProperty*>(propInfo->Prop);
+  // Create a list of the python variables for each proxy in the property vector
+  QStringList nameList;
+  for (int i = 0; i < prop->GetNumberOfProxies(); i++) {
+    vtkSMProxy* inputProxy = prop->GetProxy(i);
+    proxy_trace_info_ptr info = get_proxy_info(inputProxy);
+    if (info && (!info->PyVariable.isNull())) 
+      nameList.append(info->PyVariable);
+  }
+  if (nameList.size() == 0) 
+    return "[]";
+  if (nameList.size() == 1) 
+    return nameList.first();
+  if (nameList.size() > 1) {
+    QString nameListStr = make_comma_separated_string(nameList);
+    return QString("[%1]").arg(nameListStr);
+  }
+}
+
+//********************************************************************
+QString input_smproperty_tostring(const proxy_trace_info_ptr proxyInfo, 
+                                  const prop_trace_info_ptr propInfo)
+{
+  return proxy_smproperty_tostring(proxyInfo, propInfo);
+}
+
+//********************************************************************
+void trace_proxy_rename(const proxy_trace_info_ptr proxy_info, const char* new_name)
+{
+  if ((!proxy_info) || (proxy_info->Group != "sources"))
+    return;
+  QString old_pyvariable = proxy_info->PyVariable;
+  proxy_info->PyVariable = pyvariable_from_proxy_name(new_name);
+  proxy_info->ignore_next_unregister = true;
+  QString newName(new_name);
+  QString name_to_set = newName.replace("\"", "");
+  globals.trace_output.append(QString("RenameSource(\"%1\", %2)").arg(name_to_set).arg(old_pyvariable));
+  globals.trace_output.append(QString("%1 = %2").arg(proxy_info->PyVariable).arg(old_pyvariable));
+  globals.trace_output.append(QString("del %1").arg(old_pyvariable));
+}
+
+//********************************************************************
+proxy_trace_info_ptr trace_proxy_registered(vtkSMProxy* proxy, 
+                                         const QString& proxyGroup, 
+                                         const char* proxyName)
+{
+  //if trace_globals.verbose:
+  //  print "Proxy '%s' registered in group '%s'" % (proxyName, proxyGroup)
+  if (!globals.traced_proxy_groups.contains(proxyGroup))
+    return proxy_trace_info_ptr();
+
+  proxy_trace_info_ptr info(new proxy_trace_info(proxy, proxyGroup, proxyName));
+  globals.last_registered_proxies.append(info);
+  if (globals.capture_all_properties) {
+    vtkSMPropertyIterator* itr = proxy->NewPropertyIterator();
+    for (itr->Begin(); !itr->IsAtEnd(); itr->Next()) { 
+      vtkSMProperty* prop = itr->GetProperty();
+      if (prop->GetInformationOnly() || prop->GetIsInternal()) continue;
+      trace_property_modified(info, prop);
+    }
+  }
+  return info;
+}
+
+//********************************************************************
+prop_trace_info_ptr trace_property_modified(proxy_trace_info_ptr info, vtkSMProperty* prop)
+{
+  prop_trace_info_ptr propInfo(new prop_trace_info(info, prop));
+  //if (globals.verbose)
+  //  print "Property '%s' modifed on proxy '%s'" % (propInfo.PyVariable, info.ProxyName)
+  QString propValue;
+  if (prop->IsA("vtkSMVectorProperty"))
+    propValue = vector_smproperty_tostring(info, propInfo);
+  else if (prop->IsA("vtkSMInputProperty"))
+    propValue = input_smproperty_tostring(info, propInfo);
+  else if (prop->IsA("vtkSMProxyProperty"))
+    propValue = proxy_smproperty_tostring(info, propInfo);
+  if (!propValue.isNull()) {
+    info->Props[prop] = propValue;
+    info->ModifiedProps[propInfo->PyVariable] = propValue;
+    info->CurrentProps[propInfo->PyVariable] = propValue;
+  }
+  return propInfo;
+}
+
+//********************************************************************
+QList<proxy_trace_info_ptr> sort_proxy_info_by_group(const QList<proxy_trace_info_ptr>& infoList)
+{
+  QList<proxy_trace_info_ptr> views;
+  QList<proxy_trace_info_ptr> sources;
+  QList<proxy_trace_info_ptr> representations;
+  QList<proxy_trace_info_ptr> other;
+  foreach (proxy_trace_info_ptr i, infoList) {
+    if (i->Group == "views") views.append(i);
+    else if (i->Group == "sources") sources.append(i);
+    else if (i->Group == "representations") representations.append(i);
+    else other.append(i);
+  }
+  views.append(sources);
+  views.append(other);
+  views.append(representations);  
+  return views;
+}
+
+//********************************************************************
+void append_trace()
+{
+  // Get the list of last registered proxies in sorted order
+  QList<proxy_trace_info_ptr> modified_proxies = 
+    sort_proxy_info_by_group(globals.last_registered_proxies);
+
+  // Now append the existing proxies to the list
+  foreach (proxy_trace_info_ptr p, globals.registered_proxies)
+    modified_proxies.append(p);
+
+  foreach(proxy_trace_info_ptr info, modified_proxies) {
+    QString traceOutput = "";
+
+    // Generate list of tuples : (propName, propValue)
+    QMap<QString, QString> propNameValues;
+    QMap<QString, QString>::const_iterator aIt;
+    for (aIt = info->ModifiedProps.constBegin(); aIt!=info->ModifiedProps.constEnd(); ++aIt) {
+      QString propName = aIt.key();
+      QString propValue = aIt.value();
+      if (propIsIgnored(info, propName))
+        continue;
+
+      // Note, the 'Input' property is ignored for representations, so we are
+      // only dealing with filter proxies here.  If the 'Input' property is a
+      // single value (not a multi-input filter), then ensure the input is
+      // the active source and leave the 'Input' property out of the
+      // propNameValues list.
+      if ((propName == "Input") && (!propValue.contains("["))) {
+        proxy_trace_info_ptr inputProxyInfo = get_proxy_info(propValue);
+        ensure_active_source(inputProxyInfo);
+        continue;
+      }
+      propNameValues[propName] = propValue;
+    }
+
+    // Clear the modified prop list
+    info->ModifiedProps.clear();
+
+    // If info is in the last_registered_proxies list, then we need to add the
+    // proxy's constructor call to the trace
+    if(globals.last_registered_proxies.contains(info)) {
+      // Determine the function call to construct the proxy
+      bool setPropertiesInCtor = true;
+      QStringList ctorArgs;
+      QString extraCtorCommands = "";
+      QString ctorMethod = make_name_valid(info->Proxy->GetXMLLabel());
+      if (info->Group == "sources") {
+        // track it as the last active source now
+        globals.last_active_source = info->Proxy;
+        // maybe append the guiName property
+        if (globals.use_gui_name)
+          ctorArgs.append(QString("guiName=\"%1\"").arg(info->ProxyName));
+      }
+      if (info->Group == "representations") {
+        ctorMethod = "Show";
+        setPropertiesInCtor = false;
+        // Ensure the input proxy is the active source:
+        proxy_trace_info_ptr input_proxy_info = get_input_proxy_info_for_rep(info);
+        if (input_proxy_info)
+          ensure_active_source(input_proxy_info);
+        
+        // Ensure the view is the active view:
+        proxy_trace_info_ptr view_proxy_info = get_view_proxy_info_for_rep(info);
+        if (view_proxy_info) {
+          ensure_active_view(view_proxy_info);
+        }
+      }
+      if (info->Group == "scalar_bars") {
+        ctorMethod = "CreateScalarBar";
+        extraCtorCommands = 
+          QString("GetRenderView().Representations.append(%1)").arg(info->PyVariable);
+      }
+      if (info->Group == "views") {
+        ctorMethod = "CreateRenderView";
+        // Now track it as the last active view
+        globals.last_active_view = info->Proxy;
+        setPropertiesInCtor = false;
+      }
+      if (info->Group == "lookup_tables")
+        ctorMethod = "CreateLookupTable";
+
+
+      if (setPropertiesInCtor) {
+        QMap<QString, QString>::const_iterator aIt1;
+        for (aIt1 = propNameValues.constBegin(); aIt1!=propNameValues.constEnd(); ++aIt1) {
+          QString propName = aIt1.key();
+          QString propValue = aIt1.value();
+          ctorArgs.append(QString("%1=%2").arg(propName).arg(propValue));
+        }
+        propNameValues.clear();
+      }
+      QString ctorArgString = make_comma_separated_string(ctorArgs);
+      traceOutput = 
+        QString("%1 = %2(%3)\n%4").arg(info->PyVariable).arg(ctorMethod).arg(ctorArgString).arg(extraCtorCommands);
+    }
+    // Set properties on the proxy
+
+    QMap<QString, QString>::const_iterator aIt2;
+    for (aIt2 = propNameValues.constBegin(); aIt2!=propNameValues.constEnd(); ++aIt2) {
+      QString propName = aIt2.key();
+      QString propValue = aIt2.value();
+      traceOutput += QString("%1.%2 = %3\n").arg(info->PyVariable).arg(propName).arg(propValue);
+    }
+    if (traceOutput.length() > 0){
+      globals.trace_output.append(traceOutput);
+    }
+  }
+  foreach (proxy_trace_info_ptr p, globals.last_registered_proxies) {
+    globals.registered_proxies.append(p);
+  }
+  while (globals.last_registered_proxies.size() > 0)
+    globals.last_registered_proxies.removeLast();
+}
+
+//********************************************************************
+QString get_trace_string()
+{
+  append_trace();
+  QString s = globals.trace_output.join("\n");
+  s += globals.trace_output_endblock + "\n";
+
+  return s;
+}
+
+//********************************************************************
+void save_trace(const QString& fileName)
+{
+  QFile file(fileName);
+  if(!file.open(QFile::WriteOnly))
+    return;
+
+  QString trace = get_trace_string();
+  QTextStream out(&file);
+  out << trace;
+  file.close();
+}
+
+//********************************************************************
+//QString print_trace()
+
+//********************************************************************
+void on_proxy_registered(vtkObject* obj, unsigned long , void* , void *)
+{
+  vtkSMPythonTraceObserver* o = dynamic_cast<vtkSMPythonTraceObserver*>(obj);
+  if (!o) return;
+
+  vtkSMProxy* p = o->GetLastProxyRegistered();
+  const char* pGroup = o->GetLastProxyRegisteredGroup();
+  const char* pName = o->GetLastProxyRegisteredName();
+  if (p && pGroup && pName) {
+    proxy_trace_info_ptr proxy_info = get_proxy_info(p, false);
+    // handle source proxy rename, no-op if proxy isn't a source
+    if (proxy_info) 
+      trace_proxy_rename(proxy_info, pName);
+    else
+      trace_proxy_registered(p, pGroup, pName);
+  }
+}
+
+//********************************************************************
+void on_proxy_unregistered(vtkObject* obj, unsigned long , void* , void*)
+{
+  vtkSMPythonTraceObserver* o = dynamic_cast<vtkSMPythonTraceObserver*>(obj);
+  if (!o) return;
+
+  vtkSMProxy* p = o->GetLastProxyUnRegistered();
+  const char* pGroup = o->GetLastProxyUnRegisteredGroup();
+  const char* pName = o->GetLastProxyUnRegisteredName();
+  if (p && pGroup && pName) {
+    proxy_trace_info_ptr proxy_info = get_proxy_info(p);
+    if (proxy_info != NULL && proxy_info->Proxy != NULL) {
+      if (proxy_info->ignore_next_unregister) {
+        proxy_info->ignore_next_unregister = false;
+        return;
+      }
+      globals.trace_output.append(QString("Delete(%1)").arg(proxy_info->PyVariable));
+      if (globals.last_registered_proxies.contains(proxy_info)) {
+        int aInd = globals.last_registered_proxies.indexOf(proxy_info);
+        globals.last_registered_proxies.removeAt(aInd);
+      }
+      if (globals.registered_proxies.contains(proxy_info)) {
+        int aInd = globals.registered_proxies.indexOf(proxy_info);
+        globals.registered_proxies.removeAt(aInd);
+      }
+    }
+  }
+}
+
+//********************************************************************
+void on_property_modified(vtkObject* obj, unsigned long , void* , void*)
+{
+  vtkSMPythonTraceObserver* o = dynamic_cast<vtkSMPythonTraceObserver*>(obj);
+  if (!o) return;
+
+  const char* propName = o->GetLastPropertyModifiedName();
+  vtkSMProxy* proxy = o->GetLastPropertyModifiedProxy();
+  if ((propName != NULL) && (proxy != NULL)) {
+    vtkSMProperty* prop = proxy->GetProperty(propName);
+    if (prop->GetInformationOnly() || prop->GetIsInternal()) return;
+
+    // small hack here: some view properties are modified before the view
+    // is registered.  We don't want to call get_proxy_info until after
+    // the view is registered, so for now lets ignore these properties:
+    QStringList ignoredViewProp = ignoredViewProperties();
+    if (ignoredViewProp.contains(propName)) return;
+
+    proxy_trace_info_ptr info = get_proxy_info(proxy);
+    if ((info != NULL && info->Proxy != NULL) && (prop != NULL))
+      trace_property_modified(info, prop);
+  }
+}
+
+//********************************************************************
+void on_update_information(vtkObject*, unsigned long , void* , void*)
+{
+  append_trace();
+}
+
+//********************************************************************
+void add_observers()
+{
+  vtkCallbackCommand *aCommand = NULL;
+  vtkSMPythonTraceObserver* o = trace_observer();
+  aCommand = vtkCallbackCommand::New();
+  aCommand->SetCallback(on_proxy_registered);
+  o->AddObserver("RegisterEvent", aCommand);
+  aCommand->Delete();
+  aCommand = vtkCallbackCommand::New();
+  aCommand->SetCallback(on_proxy_unregistered);
+  o->AddObserver("UnRegisterEvent", aCommand);
+  aCommand->Delete();
+  aCommand = vtkCallbackCommand::New();
+  aCommand->SetCallback(on_property_modified);
+  o->AddObserver("PropertyModifiedEvent", aCommand);
+  aCommand->Delete();
+  aCommand = vtkCallbackCommand::New();
+  aCommand->SetCallback(on_update_information);
+  o->AddObserver("UpdateInformationEvent", aCommand);
+  aCommand->Delete();
+  globals.observer_active = true;
+}
+
+//********************************************************************
+void reset_trace_observer()
+{
+  if (myInitialised) 
+    globals.observer->Delete();
+  globals.observer = vtkSMPythonTraceObserver::New();
+  globals.observer_active = false;
+  myInitialised = true;
+}
+
+//********************************************************************
+void reset_trace_globals()
+{
+  globals.capture_all_properties = false;
+  globals.use_gui_name = false;
+  globals.verbose = false;
+  globals.active_source_at_start = 0;
+  globals.active_view_at_start = 0;
+  globals.last_active_view = 0;
+  globals.last_active_source = 0;
+  globals.last_registered_proxies.clear();
+  globals.registered_proxies.clear();
+  globals.trace_output.clear();
+  globals.trace_output << "try: pvsimple\nexcept: from pvsimple import *\n";
+  globals.trace_output_endblock = "Render()";
+  globals.traced_proxy_groups.clear();
+  globals.traced_proxy_groups << "sources"<<"representations"<<"views"<<"lookup_tables"<<"scalar_bars";
+  globals.ignored_view_properties.clear();
+  globals.ignored_view_properties << "ViewSize"<<"GUISize"<<"ViewPosition"<<"ViewTime"<<"Representations";
+  globals.ignored_representation_properties.clear();
+  globals.ignored_representation_properties << "Input";
+  reset_trace_observer();
+}
+
+//********************************************************************
+void clear_trace()
+{
+  reset_trace_globals();
+}
+
+//********************************************************************
+void stop_trace()
+{
+  reset_trace_observer();
+}
+
+//********************************************************************
+void start_trace(bool CaptureAllProperties, bool UseGuiName, bool Verbose)
+{
+  clear_trace();
+  add_observers();
+  // VSV: Has to be defined
+  //globals.active_source_at_start = simple.GetActiveSource()
+  //globals.active_view_at_start = simple.GetActiveView()
+  //globals.capture_all_properties = CaptureAllProperties
+  //globals.use_gui_name = UseGuiName
+  //globals.verbose = Verbose
+}
diff --git a/src/PVGUI/PVGUI_Trace.h b/src/PVGUI/PVGUI_Trace.h
new file mode 100644 (file)
index 0000000..de060e3
--- /dev/null
@@ -0,0 +1,188 @@
+//  Copyright (C) 2007-2008  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.
+//
+//  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   : PVGUI_Trace.h
+//  Author : Vitaly Smetannikov
+//  Module : PARAVIS
+//
+#ifndef __PARAVIS_TRACE_I_H__
+#define __PARAVIS_TRACE_I_H__
+
+#include <QString>
+#include <QStringList>
+#include <QList>
+#include <QMap>
+#include <boost/shared_ptr.hpp>
+
+class vtkSMPythonTraceObserver;
+class vtkSMProxy;
+class vtkSMProperty;
+class vtkObject;
+
+class proxy_trace_info: public QObject
+{
+  Q_OBJECT
+public:
+  proxy_trace_info(vtkSMProxy* proxy, const QString& proxyGroup, const QString& proxyName);
+
+  vtkSMProxy*            Proxy;
+  QString                Group;
+  QString                ProxyName;
+  QString                PyVariable;
+  QMap<vtkSMProperty*, QString> Props;
+  QMap<QString, QString> CurrentProps;
+  QMap<QString, QString> ModifiedProps;
+  bool                   ignore_next_unregister;
+};
+
+typedef boost::shared_ptr<proxy_trace_info> proxy_trace_info_ptr;
+
+
+
+class prop_trace_info: public QObject
+{
+  Q_OBJECT
+public:
+  prop_trace_info(proxy_trace_info_ptr proxyTraceInfo, vtkSMProperty* prop);
+
+  vtkSMProperty* Prop;
+  QString        PyVariable;
+};
+
+typedef boost::shared_ptr<prop_trace_info>  prop_trace_info_ptr;
+
+struct trace_globals
+{
+  vtkSMPythonTraceObserver* observer;
+  bool observer_active;
+  bool capture_all_properties;
+  bool use_gui_name;
+  bool verbose;
+
+  vtkSMProxy* active_source_at_start;
+  vtkSMProxy* last_active_source;
+
+  vtkSMProxy*   active_view_at_start;
+  vtkSMProxy*   last_active_view;
+
+  QList<proxy_trace_info_ptr> last_registered_proxies;
+  QList<proxy_trace_info_ptr> registered_proxies;
+
+  QStringList        trace_output;
+  QString            trace_output_endblock;
+  QStringList        traced_proxy_groups;
+  QStringList        ignored_view_properties;
+  QStringList        ignored_representation_properties;
+};
+
+
+QString make_name_valid(const QString& theName);
+
+void reset_trace_observer();
+
+void reset_trace_globals();
+
+QString pyvariable_from_proxy_name(const QString& proxy_name);
+
+vtkSMPythonTraceObserver* trace_observer();
+
+QStringList ignoredViewProperties();
+
+QStringList ignoredRepresentationProperties();
+
+bool propIsIgnored(const proxy_trace_info_ptr info, const QString& propName);
+
+void track_existing_sources();
+
+proxy_trace_info_ptr track_existing_source_proxy(vtkSMProxy* proxy, const QString& proxy_name);
+
+proxy_trace_info_ptr track_existing_view_proxy(vtkSMProxy* proxy, const QString& proxy_name);
+
+proxy_trace_info_ptr track_existing_representation_proxy(vtkSMProxy* proxy, const QString& proxy_name);
+
+proxy_trace_info_ptr track_existing_proxy(vtkSMProxy* proxy);
+
+proxy_trace_info_ptr get_proxy_info(const QString& p, bool search_existing=true);
+proxy_trace_info_ptr get_proxy_info(vtkSMProxy* p, bool search_existing=true);
+
+void ensure_active_source(const proxy_trace_info_ptr proxy_info);
+void ensure_active_view(const proxy_trace_info_ptr proxy_info);
+
+proxy_trace_info_ptr get_input_proxy_info_for_rep(const proxy_trace_info_ptr rep_info);
+proxy_trace_info_ptr get_view_proxy_info_for_rep(const proxy_trace_info_ptr rep_info);
+
+QString get_source_proxy_registration_name(vtkSMProxy* proxy);
+
+QString get_view_proxy_registration_name(vtkSMProxy* proxy);
+
+QString get_representation_proxy_registration_name(vtkSMProxy* proxy);
+
+QString make_comma_separated_string(QStringList values);
+
+QString vector_smproperty_tostring(const proxy_trace_info_ptr proxyInfo, 
+                                   const prop_trace_info_ptr propInfo);
+
+QString get_property_value_from_list_domain(const proxy_trace_info_ptr proxyInfo, 
+                                            const prop_trace_info_ptr propInfo);
+
+QString proxy_smproperty_tostring(const proxy_trace_info_ptr proxyInfo, 
+                                  const prop_trace_info_ptr propInfo);
+
+QString input_smproperty_tostring(const proxy_trace_info_ptr proxyInfo, 
+                                  const prop_trace_info_ptr propInfo);
+
+void trace_proxy_rename(const proxy_trace_info_ptr proxy_info, const char* new_name);
+
+proxy_trace_info_ptr trace_proxy_registered(vtkSMProxy* proxy, 
+                                         const QString& proxyGroup, 
+                                         const char* proxyName);
+
+prop_trace_info_ptr trace_property_modified(proxy_trace_info_ptr info, vtkSMProperty* prop);
+
+
+QList<proxy_trace_info_ptr> sort_proxy_info_by_group(const QList<proxy_trace_info_ptr>& infoList);
+
+void append_trace();
+
+QString get_trace_string();
+
+void save_trace(const QString& fileName);
+
+//QString print_trace();
+
+void on_proxy_registered(vtkObject* o, unsigned long eid, void* clientdata, void *calldata);
+
+void on_proxy_unregistered(vtkObject* o, unsigned long eid, void* clientdata, void *calldata);
+
+void on_property_modified(vtkObject* o, unsigned long eid, void* clientdata, void *calldata);
+
+void on_update_information(vtkObject* o, unsigned long eid, void* clientdata, void *calldata);
+
+void add_observers();
+
+void clear_trace();
+
+void stop_trace();
+
+void start_trace(bool CaptureAllProperties=false, bool UseGuiName=false, bool Verbose=false);
+
+
+#endif
diff --git a/src/PVGUI/PV_Events.h b/src/PVGUI/PV_Events.h
new file mode 100644 (file)
index 0000000..48326e3
--- /dev/null
@@ -0,0 +1,244 @@
+//  Copyright (C) 2007-2008  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.
+//
+//  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
+//
+//  VISU OBJECT : interactive object for VISU entities implementation
+//  File   : PV_Events.h
+//  Author : Vitaly Smetannikov 
+//  Module : PARAVIS
+//
+
+#ifndef PV_EVENTS_H
+#define PV_EVENTS_H
+
+#include "SALOME_Event.h"
+#include "SalomeApp_Study.h"
+#include "SalomeApp_Application.h"
+
+#include "SUIT_Session.h"
+
+
+/*!
+ * Definition of events
+ */
+namespace PARAVIS {
+  
+  /*!
+   * Event which returns SalomeApp_Application instance which corresponds to th given study ID
+   */
+  struct TGetGUIApplication: public SALOME_Event
+  {
+    int myStudyId;
+    typedef SalomeApp_Application* TResult;
+    TResult myResult;
+    
+     TGetGUIApplication(const int theStudyId):
+      myStudyId(theStudyId), myResult(0)
+    {}
+    
+    virtual void Execute()
+    {
+      MESSAGE("Find application for study with id = : " << myStudyId);
+      SUIT_Session* aSession = SUIT_Session::session();
+      QList<SUIT_Application*> anApplications = aSession->applications();
+      for (int i = 0; i < anApplications.count() && !myResult; i++ ){
+       if ( anApplications[i]->activeStudy() && anApplications[i]->activeStudy()->id() == myStudyId )
+         myResult = dynamic_cast<SalomeApp_Application*>( anApplications[i] );
+      }
+      if ( !myResult ) {
+       MESSAGE("Error: application is not found for study with id = : " << myStudyId);
+      }
+    }
+  };
+  
+  /*!
+   * Parent event for all events what is going to work with PARAVIS module instance
+   */
+  struct TModuleEvent: public SALOME_Event
+  {
+    SalomeApp_Application* myApp;
+
+    TModuleEvent(SalomeApp_Application* theApp ) :
+      myApp(theApp)
+    {}
+
+      //! Returns pointer on PARAVIS module instance
+    PVGUI_Module* getModule() 
+    {
+      PVGUI_Module* aPVModule = 0;
+      CAM_Application::ModuleList aList = myApp->modules();
+      foreach(CAM_Module* aModule, aList) {
+        if (aModule->moduleName() == "ParaViS") {
+          aPVModule = dynamic_cast<PVGUI_Module*>(aModule);
+          break;
+        }
+      }
+      return aPVModule;
+    }
+  };
+
+  /*!
+   * Event which activates PARAVIS module if it is not active
+   */
+  struct TActivateModule: public TModuleEvent
+  {
+    TActivateModule(SalomeApp_Application* theApp ) :
+      TModuleEvent(theApp)
+   {}
+    
+    virtual void Execute()
+    {
+      PVGUI_Module* aPVModule = getModule();
+      if ((aPVModule == 0) || (myApp->activeModule() != aPVModule)) {
+        myApp->activateModule("ParaViS");
+      }
+    }
+  };
+
+  /*!
+   * Returns trace string collected in PARAVIS module in current session
+   */
+  struct TGetTrace: public TModuleEvent
+  {
+    typedef const char* TResult;
+    TResult myResult;
+    TGetTrace(SalomeApp_Application* theApp) :
+      TModuleEvent(theApp)
+    {
+      myResult = "";
+    }
+
+    virtual void Execute()
+    {
+      PVGUI_Module* aPVModule = getModule();
+      if (aPVModule)
+        myResult = qPrintable(aPVModule->printTrace());
+    }
+  };
+
+  /*!
+   * Parent event for all operations with files across PARAVIS module
+   */
+  struct TParavisFileEvent: public TModuleEvent
+  {
+    const char* myName;
+
+    TParavisFileEvent(SalomeApp_Application* theApp, const char* theFileName ) :
+      TModuleEvent(theApp), myName(theFileName)
+    {}
+  };
+
+  /*!
+   * Event to save trace string inte disk file
+   */
+  struct TSaveTrace: public TParavisFileEvent
+  {
+    TSaveTrace(SalomeApp_Application* theApp, const char* theFileName ) :
+      TParavisFileEvent(theApp, theFileName)
+    {}
+    
+    virtual void Execute()
+    {
+      PVGUI_Module* aPVModule = getModule();
+      if (aPVModule)
+        aPVModule->saveTrace(myName);
+    }
+  };
+
+
+  /*!
+   * Event to import file to PARAVIS
+   */
+  struct TImportFile: public TParavisFileEvent
+  {
+    TImportFile(SalomeApp_Application* theApp, const char* theFileName ) :
+      TParavisFileEvent(theApp, theFileName)
+    {}
+    
+    virtual void Execute()
+    {
+      PVGUI_Module* aPVModule = getModule();
+      if (aPVModule)
+        aPVModule->openFile(myName);
+    }
+  };
+
+
+  /*!
+   * Event to save current Paraview state.
+   * This event is used for Study saving
+   */
+  struct TSaveStateFile: public TParavisFileEvent
+  {
+    TSaveStateFile(SalomeApp_Application* theApp, const char* theFileName ) :
+      TParavisFileEvent(theApp, theFileName)      
+    {}
+    
+    virtual void Execute()
+    {
+      PVGUI_Module* aPVModule = getModule();
+      if (aPVModule)
+        aPVModule->saveParaviewState(myName);
+    }
+  };
+
+
+  /*!
+   * Event to restore Paraview state from disk file.
+   * This event is used for Study restoring
+   */
+  struct TLoadStateFile: public TParavisFileEvent
+  {
+    TLoadStateFile(SalomeApp_Application* theApp, const char* theFileName ) :
+      TParavisFileEvent(theApp, theFileName)      
+    {}
+    
+    virtual void Execute()
+    {
+      PVGUI_Module* aPVModule = getModule();
+      if (aPVModule)
+        aPVModule->loadParaviewState(myName);
+    }
+  };
+
+  /*!
+   * Returns currently active Paraview server
+   */
+  struct TGetActiveServer: public TModuleEvent
+  {
+    typedef pqServer* TResult;
+    TResult myResult;
+
+    TGetActiveServer(SalomeApp_Application* theApp ) :
+      TModuleEvent(theApp), myResult(0)   
+    {}
+    
+    virtual void Execute()
+    {
+      PVGUI_Module* aPVModule = getModule();
+      if (aPVModule)
+        myResult = aPVModule->getActiveServer();
+    }
+  };
+
+};
+
+
+#endif  //PV_EVENTS_H
diff --git a/src/PVGUI/PV_I.h b/src/PVGUI/PV_I.h
new file mode 100644 (file)
index 0000000..cb9edae
--- /dev/null
@@ -0,0 +1,46 @@
+//  Copyright (C) 2007-2008  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.
+//
+//  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   : PARAVIS_I.hxx
+//  Author : Vitaly Smetannikov
+//  Module : PARAVIS
+//
+#ifndef _PARAVIS_I_HXX_
+#define _PARAVIS_I_HXX_
+
+#ifdef WNT
+# if defined PARAVIS_I_EXPORTS || defined PARAVISEngineImpl_EXPORTS
+#  define PARAVIS_I_EXPORT __declspec( dllexport )
+# else
+#  define PARAVIS_I_EXPORT __declspec( dllimport )
+# endif
+
+# define COPY_COMMAND           "copy /Y"
+# define MOVE_COMMAND           "move /Y"
+# define DELETE_COMMAND         "del /F"
+#else
+# define PARAVIS_I_EXPORT
+# define COPY_COMMAND           "cp"
+# define MOVE_COMMAND           "mv"
+# define DELETE_COMMAND         "rm -f"
+#endif
+
+#endif
diff --git a/src/PVGUI/PV_Tools.cxx b/src/PVGUI/PV_Tools.cxx
new file mode 100644 (file)
index 0000000..e6644d4
--- /dev/null
@@ -0,0 +1,105 @@
+//  Copyright (C) 2007-2008  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.
+//
+//  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
+//
+//  VISU OBJECT : interactive object for VISU entities implementation
+//  File   : PV_Tools.cxx
+//  Author : Alexey PETROV
+//  Module : VISU
+//
+#include "PV_Tools.h"  
+#include "PARAVIS_Gen_i.hh"
+
+#include <omnithread.h>
+#include CORBA_SERVER_HEADER(SALOME_Session)
+#include CORBA_SERVER_HEADER(SALOME_ModuleCatalog)
+
+#include <SALOME_NamingService.hxx>
+
+#include <QString>
+
+namespace PARAVIS
+{
+//----------------------------------------------------------------------------
+  SALOMEDS::ListOfFileNames* GetListOfFileNames(const QStringList& theFileNames)
+  {
+    SALOMEDS::ListOfFileNames_var aListOfFileNames = new SALOMEDS::ListOfFileNames;
+    if(!theFileNames.isEmpty()){
+      aListOfFileNames->length(theFileNames.size());
+      int i = 0;
+      foreach (QString aName, theFileNames) {
+        aListOfFileNames[i] = qPrintable(aName);
+        i++;
+      }
+    }
+    return aListOfFileNames._retn();
+  }
+
+  //----------------------------------------------------------------------------
+  SALOMEDS::SComponent_var FindOrCreateParaVisComponent(SALOMEDS::Study_ptr theStudyDocument)
+  {
+    SALOMEDS::SComponent_var aSComponent = theStudyDocument->FindComponent("PARAVIS");
+    if (aSComponent->_is_nil()) {
+      SALOMEDS::StudyBuilder_var aStudyBuilder = theStudyDocument->NewBuilder();
+      aStudyBuilder->NewCommand();
+      int aLocked = theStudyDocument->GetProperties()->IsLocked();
+      if (aLocked) theStudyDocument->GetProperties()->SetLocked(false);
+      aSComponent = aStudyBuilder->NewComponent("PARAVIS");
+      SALOMEDS::GenericAttribute_var anAttr = 
+        aStudyBuilder->FindOrCreateAttribute(aSComponent, "AttributeName");
+      SALOMEDS::AttributeName_var aName = SALOMEDS::AttributeName::_narrow(anAttr);
+      
+      CORBA::ORB_var anORB = PARAVIS_Gen_i::GetORB();
+      SALOME_NamingService *NamingService = new SALOME_NamingService( anORB );
+      CORBA::Object_var objVarN = NamingService->Resolve("/Kernel/ModulCatalog");
+      SALOME_ModuleCatalog::ModuleCatalog_var Catalogue  = 
+        SALOME_ModuleCatalog::ModuleCatalog::_narrow(objVarN);
+      SALOME_ModuleCatalog::Acomponent_var Comp = Catalogue->GetComponent( "PARAVIS" );
+      if ( !CORBA::is_nil(Comp) ) {
+        aName->SetValue( Comp->componentusername() );
+      }
+      
+      anAttr = aStudyBuilder->FindOrCreateAttribute(aSComponent, "AttributePixMap");
+      SALOMEDS::AttributePixMap_var aPixmap = SALOMEDS::AttributePixMap::_narrow(anAttr);
+      aPixmap->SetPixMap( "pqAppIcon16.png" );
+      
+      PARAVIS_Gen_var aParaVisGen = PARAVIS_Gen_i::GetParavisGenImpl()->_this();
+      aStudyBuilder->DefineComponentInstance(aSComponent, aParaVisGen);
+      if (aLocked) 
+        theStudyDocument->GetProperties()->SetLocked(true);
+      aStudyBuilder->CommitCommand();
+    }
+    return aSComponent;
+  }
+
+  PARAVIS_Base_i* GET_SERVANT(CORBA::Object_ptr aObj) {
+    //dynamic_cast<PARAVIS_Base_i*>(PARAVIS_Gen_i::GetPOA()->reference_to_servant(OBJ).in())
+    if (CORBA::is_nil(aObj))
+      return NULL;
+    try {
+      PortableServer::POA_ptr aPOA = PARAVIS_Gen_i::GetPOA();
+      PortableServer::ServantBase_var aServant = aPOA->reference_to_servant(aObj);
+      return dynamic_cast<PARAVIS_Base_i*>(aServant.in());
+    } catch (...) {
+      MESSAGE("GET_SERVANT: Unknown exception!!!");
+    }
+    return NULL;
+  }
+};
diff --git a/src/PVGUI/PV_Tools.h b/src/PVGUI/PV_Tools.h
new file mode 100644 (file)
index 0000000..9900b47
--- /dev/null
@@ -0,0 +1,54 @@
+//  Copyright (C) 2007-2008  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.
+//
+//  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   : PV_Tools.h
+//  Author : Vitaly Smetannikov
+//  Module : PARAVIS
+//
+
+#ifndef __PV_TOOLS_H__
+#define __PV_TOOLS_H__
+
+#include "SALOMEconfig.h"
+#include CORBA_SERVER_HEADER(SALOMEDS)
+#include CORBA_SERVER_HEADER(SALOMEDS_Attributes)
+
+//#include <string>
+//#include <vector>
+
+#include <QStringList>
+
+namespace PARAVIS
+{
+  class PARAVIS_Base_i;
+
+  //SALOMEDS::ListOfFileNames* GetListOfFileNames(const std::vector<std::string>& theFileNames);
+  SALOMEDS::ListOfFileNames* GetListOfFileNames(const QStringList& theFileNames);
+
+
+  SALOMEDS::SComponent_var FindOrCreateParaVisComponent(SALOMEDS::Study_ptr theStudyDocument);
+
+  PARAVIS_Base_i* GET_SERVANT(CORBA::Object_ptr aObj);
+  //dynamic_cast<PARAVIS_Base_i*>(PARAVIS_Gen_i::GetPOA()->reference_to_servant(OBJ).in())
+
+};
+
+#endif
index 7b2559f5921df91fcdd21dd3ad7ac307286f9a86..d70865a40dad0d468575381e999b7d721c77d5e3 100644 (file)
         <source>TOOL_VCR_CONTROLS</source>
         <translation>VCR Controls</translation>
     </message>
+    <message>
+        <source>PREF_STOP_TRACE</source>
+        <translation>Deactivate Trace (for next session only)</translation>
+    </message>
+    <message>
+        <source>TIT_TRACE</source>
+        <translation>Trace</translation>
+    </message>
 </context>
 </TS>
diff --git a/src/PV_SWIG/Makefile.am b/src/PV_SWIG/Makefile.am
new file mode 100644 (file)
index 0000000..732c24e
--- /dev/null
@@ -0,0 +1,30 @@
+#  Copyright (C) 2007-2008  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.
+#
+#  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
+#
+#  VISU VISU_SWIG : binding of C++ implementation and Python
+#  File   : Makefile.am
+#  Author : Paul RASCLE, EDF
+#  Module : VISU
+#
+include $(top_srcdir)/adm_local/unix/make_common_starter.am
+
+dist_salomescript_DATA = paravis.py paravisSM.py pvsimple.py
+
diff --git a/src/PV_SWIG/paravis.py b/src/PV_SWIG/paravis.py
new file mode 100644 (file)
index 0000000..d330fc7
--- /dev/null
@@ -0,0 +1,100 @@
+#  Copyright (C) 2007-2008  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.
+#
+#  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
+#
+#  VISU VISU_SWIG : binding of C++ implementation and Python
+#  File   : paravis.py
+#  Module : PARAVIS
+#
+
+import os, new
+
+import PARAVIS
+import SALOME
+import SALOME_Session_idl
+import SALOMEDS
+import SALOME_ModuleCatalog
+from omniORB import CORBA
+from time import sleep
+from salome import *
+
+myORB = None
+myNamingService = None
+myLifeCycleCORBA = None
+myNamingService = None
+myLocalStudyManager = None
+myLocalStudy = None
+myLocalParavis = None
+myDelay = None
+mySession = None
+
+## Initialization of paravis server
+def Initialize(theORB, theNamingService, theLifeCycleCORBA, theStudyManager, theStudy, theDelay) :
+    global myORB, myNamingService, myLifeCycleCORBA, myLocalStudyManager, myLocalStudy
+    global mySession, myDelay
+    myDelay = theDelay
+    myORB = theORB
+    myNamingService = theNamingService
+    myLifeCycleCORBA = theLifeCycleCORBA
+    myLocalStudyManager = theStudyManager
+    while mySession == None:
+        mySession = myNamingService.Resolve("/Kernel/Session")
+    mySession = mySession._narrow(SALOME.Session)
+    mySession.GetInterface()
+    myDelay = theDelay
+    sleep(myDelay)
+    myLocalParavis = myLifeCycleCORBA.FindOrLoadComponent("FactoryServer", "PARAVIS")
+    myLocalStudy = theStudy
+    myLocalParavis.ActivateModule()
+    return myLocalParavis
+
+
+def ImportFile(theFileName):
+    "Import a file of any format supported by ParaView"
+    myParavis.ImportFile(theFileName)
+
+
+def createFunction(theName):
+    "Create function - constructor of Paravis object"
+    def MyFunction():
+        return myParavis.CreateClass(theName)
+    return MyFunction
+
+
+def createConstructors():
+    "Create constructor functions according to list of extracted classes"
+    g = globals()
+    aClassNames = myParavis.GetClassesList();
+    for aName in aClassNames:
+        g[aName] = createFunction(aName)
+
+## Initialize of a PARAVIS interface  
+myParavis = Initialize(orb, naming_service,lcc,myStudyManager,myStudy, 2)
+
+## Initialize constructor functions
+createConstructors()
+
+## Initialize Paravis static objects
+vtkSMObject = vtkSMObject()
+vtkProcessModule = vtkProcessModule()
+vtkPVPythonModule = vtkPVPythonModule()
+vtkSMProxyManager = vtkSMProxyManager()
+
+
diff --git a/src/PV_SWIG/paravisSM.py b/src/PV_SWIG/paravisSM.py
new file mode 100644 (file)
index 0000000..371b851
--- /dev/null
@@ -0,0 +1,2835 @@
+r"""servermanager is a module for using paraview server manager in Python.
+One can always use the server manager API directly. However, this module
+provides an interface easier to use from Python by wrapping several VTK
+classes around Python classes.
+
+Note that, upon load, this module will create several sub-modules: sources,
+filters and rendering. These modules can be used to instantiate specific
+proxy types. For a list, try "dir(servermanager.sources)"
+
+A simple example:
+  from paraview.servermanager import *
+
+  # Creates a new built-in connection and makes it the active connection.
+  Connect()
+
+  # Creates a new render view on the active connection.
+  renModule = CreateRenderView()
+
+  # Create a new sphere proxy on the active connection and register it
+  # in the sources group.
+  sphere = sources.SphereSource(registrationGroup="sources", ThetaResolution=16, PhiResolution=32)
+
+  # Create a representation for the sphere proxy and adds it to the render
+  # module.
+  display = CreateRepresentation(sphere, renModule)
+
+  renModule.StillRender()
+"""
+
+
+
+import re, os, new, sys
+from paravis import *
+
+
+
+def _wrap_property(proxy, smproperty):
+    """ Internal function.
+    Given a server manager property and its domains, returns the
+    appropriate python object.
+    """
+    property = None
+    if smproperty.IsA("vtkSMStringVectorProperty"):
+        al = smproperty.GetDomain("array_list")
+        if  al and al.IsA("vtkSMArraySelectionDomain") and smproperty.GetRepeatable():
+            property = ArrayListProperty(proxy, smproperty)
+        elif al and al.IsA("vtkSMArrayListDomain") and smproperty.GetNumberOfElements() == 5:
+            property = ArraySelectionProperty(proxy, smproperty)
+        else:
+            iter = smproperty.NewDomainIterator()
+            isFileName = False
+            while not iter.IsAtEnd():
+                if iter.GetDomain().IsA("vtkSMFileListDomain"):
+                    isFileName = True
+                    break
+                iter.Next()
+            iter.UnRegister(None)
+            if isFileName:
+                property = FileNameProperty(proxy, smproperty)
+            elif _make_name_valid(smproperty.GetXMLLabel()) == 'ColorArrayName':
+                property = ColorArrayProperty(proxy, smproperty)
+            else:
+                property = VectorProperty(proxy, smproperty)
+    elif smproperty.IsA("vtkSMVectorProperty"):
+        if smproperty.IsA("vtkSMIntVectorProperty") and smproperty.GetDomain("enum"):
+            property = EnumerationProperty(proxy, smproperty)
+        else:
+            property = VectorProperty(proxy, smproperty)
+    elif smproperty.IsA("vtkSMInputProperty"):
+        property = InputProperty(proxy, smproperty)
+    elif smproperty.IsA("vtkSMProxyProperty"):
+        property = ProxyProperty(proxy, smproperty)
+    else:
+        property = Property(proxy, smproperty)
+    return property
+
+class Proxy(object):
+    """Proxy for a server side object. A proxy manages the lifetime of
+    one or more server manager objects. It also provides an interface
+    to set and get the properties of the server side objects. These
+    properties are presented as Python properties. For example,
+    you can set a property Foo using the following:
+     proxy.Foo = (1,2)
+    or
+     proxy.Foo.SetData((1,2))
+    or
+     proxy.Foo[0:2] = (1,2)
+    For more information, see the documentation of the property which
+    you can obtain with
+    help(proxy.Foo).
+
+    This class also provides an iterator which can be used to iterate
+    over all properties.
+    eg:
+      proxy = Proxy(proxy=smproxy)
+      for property in proxy:
+          print property
+
+    For advanced users:
+    This is a python class that wraps a vtkSMProxy.. Makes it easier to
+    set/get properties.
+    Instead of:
+     proxy.GetProperty("Foo").SetElement(0, 1)
+     proxy.GetProperty("Foo").SetElement(0, 2)
+    you can do:
+     proxy.Foo = (1,2)
+    or
+     proxy.Foo.SetData((1,2))
+    or
+     proxy.Foo[0:2] = (1,2)
+    Instead of:
+      proxy.GetProperty("Foo").GetElement(0)
+    you can do:
+      proxy.Foo.GetData()[0]
+    or
+      proxy.Foo[0]
+    For proxy properties, you can use append:
+     proxy.GetProperty("Bar").AddProxy(foo)
+    you can do:
+     proxy.Bar.append(foo)
+    Properties support most of the list API. See VectorProperty and
+    ProxyProperty documentation for details.
+
+    Please note that some of the methods accessible through the Proxy
+    class are not listed by help() because the Proxy objects forward
+    unresolved attributes to the underlying object. To get the full list,
+    see also dir(proxy.SMProxy). See also the doxygen based documentation
+    of the vtkSMProxy C++ class.
+    """
+
+    def __init__(self, **args):
+        """ Default constructor. It can be used to initialize properties
+        by passing keyword arguments where the key is the name of the
+        property. In addition registrationGroup and registrationName (optional)
+        can be specified (as keyword arguments) to automatically register
+        the proxy with the proxy manager. """
+        self.add_attribute('Observed', None)
+        self.add_attribute('ObserverTag', -1)
+        self.add_attribute('_Proxy__Properties', {})
+        self.add_attribute('_Proxy__LastAttrName', None)
+        self.add_attribute('SMProxy', None)
+        self.add_attribute('Port', 0)
+
+        if 'port' in args:
+            self.Port = args['port']
+            del args['port']
+
+        if 'proxy' in args:
+            self.InitializeFromProxy(args['proxy'])
+            del args['proxy']
+        else:
+            self.Initialize()
+        if 'registrationGroup' in args:
+            registrationGroup = args['registrationGroup']
+            del args['registrationGroup']
+            registrationName = self.SMProxy.GetSelfIDAsString()
+            if 'registrationName' in args:
+                registrationName = args['registrationName']
+                del args['registrationName']
+            pxm = ProxyManager()
+            pxm.RegisterProxy(registrationGroup, registrationName, self.SMProxy)
+        for key in args.keys():
+            setattr(self, key, args[key])
+        self.UpdateVTKObjects()
+        # Visit all properties so that they are created
+        for prop in self:
+            pass
+
+    def __setattr__(self, name, value):
+        try:
+            setter = getattr(self.__class__, name)
+            setter = setter.__set__
+        except AttributeError:
+            if not hasattr(self, name):
+                raise AttributeError("Attribute %s does not exist. " % name +
+                  " This class does not allow addition of new attributes to avoid " +
+                  "mistakes due to typos. Use add_attribute() if you really want " +
+                  "to add this attribute.")
+            self.__dict__[name] = value
+        else:
+            setter(self, value)
+
+    def add_attribute(self, name, value):
+        self.__dict__[name] = value
+
+    def __del__(self):
+        """Destructor. Cleans up all observers as well as remove
+        the proxy from the _pyproxies dictionary"""
+        # Make sure that we remove observers we added
+        if self.Observed:
+            observed = self.Observed
+            tag = self.ObserverTag
+            self.Observed = None
+            self.ObserverTag = -1
+            observed.RemoveObserver(tag)
+        if self.SMProxy and (self.SMProxy, self.Port) in _pyproxies:
+            del _pyproxies[(self.SMProxy, self.Port)]
+
+    def InitializeFromProxy(self, aProxy):
+        """Constructor. Assigns proxy to self.SMProxy, updates the server
+        object as well as register the proxy in _pyproxies dictionary."""
+        import weakref
+        self.SMProxy = aProxy
+        self.SMProxy.UpdateVTKObjects()
+        _pyproxies[(self.SMProxy, self.Port)] = weakref.ref(self)
+
+    def Initialize(self):
+        "Overridden by the subclass created automatically"
+        pass
+
+    def __eq__(self, other):
+        "Returns true if the underlying SMProxies are the same."
+        if isinstance(other, Proxy):
+            ## VSV using IsSame instead
+            return self.SMProxy.IsSame(other.SMProxy)
+        return self.SMProxy.IsSame(other)
+
+    def __ne__(self, other):
+        "Returns false if the underlying SMProxies are the same."
+        return not self.__eq__(other)
+
+    def __iter__(self):
+        "Creates an iterator for the properties."
+        return PropertyIterator(self)
+
+    def SetPropertyWithName(self, pname, arg):
+        """Generic method for setting the value of a property."""
+        prop = self.GetProperty(pname)
+        if prop is None:
+            raise RuntimeError, "Property %s does not exist. Please check the property name for typos." % pname
+        prop.SetData(arg)
+
+    def GetPropertyValue(self, name):
+        """Returns a scalar for properties with 1 elements, the property
+        itself for vectors."""
+        p = self.GetProperty(name)
+        if isinstance(p, VectorProperty):
+            if p.GetNumberOfElements() == 1 and not p.GetRepeatable():
+                if p.SMProperty.IsA("vtkSMStringVectorProperty") or not p.GetArgumentIsArray():
+                    return p[0]
+        elif isinstance(p, InputProperty):
+            if not p.GetMultipleInput():
+                if len(p) > 0:
+                    return p[0]
+                else:
+                    return None
+        elif isinstance(p, ProxyProperty):
+            if not p.GetRepeatable():
+                if len(p) > 0:
+                    return p[0]
+                else:
+                    return None
+        return p
+
+    def GetProperty(self, name):
+        """Given a property name, returns the property object."""
+        if name in self.__Properties and self.__Properties[name]():
+            return self.__Properties[name]()
+        smproperty = self.SMProxy.GetProperty(name)
+        # Maybe they are looking by the label. Try to match that.
+        if not smproperty:
+            iter = PropertyIterator(self)
+            for prop in iter:
+                if name == _make_name_valid(iter.PropertyLabel):
+                    smproperty = prop.SMProperty
+                    break
+        if smproperty:
+            property = _wrap_property(self, smproperty)
+            if property is not None:
+                import weakref
+                self.__Properties[name] = weakref.ref(property)
+            return property
+        return None
+
+    def ListProperties(self):
+        """Returns a list of all property names on this proxy."""
+        property_list = []
+        iter = self.__iter__()
+        for property in iter:
+            name = _make_name_valid(iter.PropertyLabel)
+            if name:
+                property_list.append(name)
+        return property_list
+
+    def __ConvertArgumentsAndCall(self, *args):
+        """ Internal function.
+        Used to call a function on SMProxy. Converts input and
+        output values as appropriate.
+        """
+        newArgs = []
+        for arg in args:
+            if issubclass(type(arg), Proxy) or isinstance(arg, Proxy):
+                newArgs.append(arg.SMProxy)
+            else:
+                newArgs.append(arg)
+        func = getattr(self.SMProxy, self.__LastAttrName)
+        retVal = func(*newArgs)
+        if type(retVal) is type(self.SMProxy) and retVal.IsA("vtkSMProxy"):
+            return _getPyProxy(retVal)
+        elif type(retVal) is type(self.SMProxy) and retVal.IsA("vtkSMProperty"):
+            return _wrap_property(self, retVal)
+        else:
+            return retVal
+
+    def __GetActiveCamera(self):
+        """ This method handles GetActiveCamera specially. It adds
+        an observer to the camera such that everytime it is modified
+        the render view updated"""
+        import weakref
+        c = self.SMProxy.GetActiveCamera()
+        # VSV: Observers are not supported
+##         if not c.HasObserver("ModifiedEvent"):
+##             self.ObserverTag =c.AddObserver("ModifiedEvent", _makeUpdateCameraMethod(weakref.ref(self)))
+##             self.Observed = c
+        return c
+
+    def __getattr__(self, name):
+        """With the exception of a few overloaded methods,
+        returns the SMProxy method"""
+        if not self.SMProxy:
+            raise AttributeError("class has no attribute %s" % name)
+            return None
+        # Handle GetActiveCamera specially.
+        if name == "GetActiveCamera" and \
+           hasattr(self.SMProxy, "GetActiveCamera"):
+            return self.__GetActiveCamera
+        if name == "SaveDefinition" and hasattr(self.SMProxy, "SaveDefinition"):
+            return self.__SaveDefinition
+        # If not a property, see if SMProxy has the method
+        try:
+            proxyAttr = getattr(self.SMProxy, name)
+            self.__LastAttrName = name
+            return self.__ConvertArgumentsAndCall
+        except:
+            pass
+        return getattr(self.SMProxy, name)
+
+class SourceProxy(Proxy):
+    """Proxy for a source object. This class adds a few methods to Proxy
+    that are specific to sources. It also provides access to the output
+    ports. Output ports can be accessed by name or index:
+    > op = source[0]
+    or
+    > op = source['some name'].
+    """
+    def UpdatePipeline(self, time=None):
+        """This method updates the server-side VTK pipeline and the associated
+        data information. Make sure to update a source to validate the output
+        meta-data."""
+        if time:
+            self.SMProxy.UpdatePipeline(time)
+        else:
+            self.SMProxy.UpdatePipeline()
+        # Fetch the new information. This is also here to cause a receive
+        # on the client side so that progress works properly.
+        self.SMProxy.GetDataInformation()
+
+    def FileNameChanged(self):
+        "Called when the filename of a source proxy is changed."
+        self.UpdatePipelineInformation()
+
+    def UpdatePipelineInformation(self):
+        """This method updates the meta-data of the server-side VTK pipeline and
+        the associated information properties"""
+        self.SMProxy.UpdatePipelineInformation()
+
+    def GetDataInformation(self, idx=None):
+        """This method returns a DataInformation wrapper around a
+        vtkPVDataInformation"""
+        if not idx:
+            idx = self.Port
+        if self.SMProxy:
+            return DataInformation( \
+                self.SMProxy.GetDataInformation(idx), \
+                self.SMProxy, idx)
+
+    def __getitem__(self, idx):
+        """Given a slice, int or string, returns the corresponding
+        output port"""
+        if isinstance(idx, slice):
+            indices = idx.indices(self.SMProxy.GetNumberOfOutputPorts())
+            retVal = []
+            for i in range(*indices):
+                retVal.append(OutputPort(self, i))
+            return retVal
+        elif isinstance(idx, int):
+            if idx >= self.SMProxy.GetNumberOfOutputPorts() or idx < 0:
+                raise IndexError
+            return OutputPort(self, idx)
+        else:
+            return OutputPort(self, self.SMProxy.GetOutputPortIndex(idx))
+
+    def GetPointDataInformation(self):
+        """Returns the associated point data information."""
+        self.UpdatePipeline()
+        return FieldDataInformation(self.SMProxy, self.Port, "PointData")
+
+    def GetCellDataInformation(self):
+        """Returns the associated cell data information."""
+        self.UpdatePipeline()
+        return FieldDataInformation(self.SMProxy, self.Port, "CellData")
+
+    def GetFieldDataInformation(self):
+        """Returns the associated cell data information."""
+        self.UpdatePipeline()
+        return FieldDataInformation(self.SMProxy, self.Port, "FieldData")
+
+    PointData = property(GetPointDataInformation, None, None, "Returns point data information")
+    CellData = property(GetCellDataInformation, None, None, "Returns cell data information")
+    FieldData = property(GetFieldDataInformation, None, None, "Returns field data information")
+
+
+class ExodusIIReaderProxy(SourceProxy):
+    """Special class to define convenience functions for array
+    selection."""
+
+    def FileNameChanged(self):
+        "Called when the filename changes. Selects all variables."
+        SourceProxy.FileNameChanged(self)
+        self.SelectAllVariables()
+
+    def SelectAllVariables(self):
+        "Select all available variables for reading."
+        for prop in ('PointVariables', 'EdgeVariables', 'FaceVariables',
+                     'ElementVariables', 'GlobalVariables'):
+            f = getattr(self, prop)
+            f.SelectAll()
+
+    def DeselectAllVariables(self):
+        "Deselects all variables."
+        for prop in ('PointVariables', 'EdgeVariables', 'FaceVariables',
+                     'ElementVariables', 'GlobalVariables'):
+            f = getattr(self, prop)
+            f.DeselectAll()
+
+class Property(object):
+    """Generic property object that provides access to one of the properties of
+    a server object. This class does not allow setting/getting any values but
+    provides an interface to update a property using __call__. This can be used
+    for command properties that correspond to function calls without arguments.
+    For example,
+    > proxy.Foo()
+    would push a Foo property which may cause the proxy to call a Foo method
+    on the actual VTK object.
+
+    For advanced users:
+    Python wrapper around a vtkSMProperty with a simple interface.
+    In addition to all method provided by vtkSMProperty (obtained by
+    forwarding unknown attributes requests to the underlying SMProxy),
+    Property and sub-class provide a list API.
+
+    Please note that some of the methods accessible through the Property
+    class are not listed by help() because the Property objects forward
+    unresolved attributes to the underlying object. To get the full list,
+    see also dir(proxy.SMProperty). See also the doxygen based documentation
+    of the vtkSMProperty C++ class.
+    """
+    def __init__(self, proxy, smproperty):
+        """Default constructor. Stores a reference to the proxy."""
+        import weakref
+        self.SMProperty = smproperty
+        self.Proxy = proxy
+
+    def __repr__(self):
+        """Returns a string representation containing property name
+        and value"""
+        if not type(self) is Property:
+            if self.GetData() is not None:
+                repr = self.GetData().__repr__()
+            else:
+                repr = "None"
+        else:
+            repr = "Property name= "
+            name = self.Proxy.GetPropertyName(self.SMProperty)
+            if name:
+                repr += name
+            else:
+                repr += "Unknown"
+
+        return repr
+
+    def __call__(self):
+        """Forces a property update using InvokeCommand."""
+        if type(self) is Property:
+            self.Proxy.SMProxy.InvokeCommand(self._FindPropertyName())
+        else:
+            raise RuntimeError, "Cannot invoke this property"
+
+    def _FindPropertyName(self):
+        "Returns the name of this property."
+        return self.Proxy.GetPropertyName(self.SMProperty)
+
+    def _UpdateProperty(self):
+        "Pushes the value of this property to the server."
+        # For now, we are updating all properties. This is due to an
+        # issue with the representations. Their VTK objects are not
+        # created until Input is set therefore, updating a property
+        # has no effect. Updating all properties everytime one is
+        # updated has the effect of pushing values set before Input
+        # when Input is updated.
+        # self.Proxy.SMProxy.UpdateProperty(self._FindPropertyName())
+        self.Proxy.SMProxy.UpdateVTKObjects()
+
+    def __getattr__(self, name):
+        "Unknown attribute requests get forwarded to SMProperty."
+        return getattr(self.SMProperty, name)
+
+class GenericIterator(object):
+    """Iterator for container type objects"""
+
+    def __init__(self, obj):
+        self.Object = obj
+        self.index = 0
+
+    def __iter__(self):
+        return self
+
+    def next(self):
+        if self.index >= len(self.Object):
+            raise StopIteration
+
+        idx = self.index
+        self.index += 1
+        return self.Object[idx]
+
+class VectorProperty(Property):
+    """A VectorProperty provides access to one or more values. You can use
+    a slice to get one or more property values:
+    > val = property[2]
+    or
+    > vals = property[0:5:2]
+    You can use a slice to set one or more property values:
+    > property[2] = val
+    or
+    > property[1:3] = (1,2)
+    """
+    def ConvertValue(self, value):
+        return value
+
+    def __len__(self):
+        """Returns the number of elements."""
+        return self.SMProperty.GetNumberOfElements()
+
+    def __iter__(self):
+        """Implementation of the sequence API"""
+        return GenericIterator(self)
+
+    def __setitem__(self, idx, value):
+        """Given a list or tuple of values, sets a slice of values [min, max)"""
+        if isinstance(idx, slice):
+            indices = idx.indices(len(self))
+            for i, j in zip(range(*indices), value):
+                self.SMProperty.SetElement(i, self.ConvertValue(j))
+            self._UpdateProperty()
+        elif idx >= len(self) or idx < 0:
+            raise IndexError
+        else:
+            self.SMProperty.SetElement(idx, self.ConvertValue(value))
+            self._UpdateProperty()
+
+    def GetElement(self, index):
+        return self.SMProperty.GetElement(index)
+
+    def __getitem__(self, idx):
+        """Returns the range [min, max) of elements. Raises an IndexError
+        exception if an argument is out of bounds."""
+        ls = len(self)
+        if isinstance(idx, slice):
+            indices = idx.indices(ls)
+            retVal = []
+            for i in range(*indices):
+               retVal.append(self.GetElement(i))
+            return retVal
+        elif idx >= ls:
+            raise IndexError
+        elif idx < 0:
+            idx = ls + idx
+            if idx < 0:
+                raise IndexError
+
+        return self.GetElement(idx)
+
+    def GetData(self):
+        "Returns all elements as either a list or a single value."
+        property = self.SMProperty
+        if property.GetRepeatable() or \
+           property.GetNumberOfElements() > 1:
+            return self[0:len(self)]
+        elif property.GetNumberOfElements() == 1:
+            return self.GetElement(0)
+
+    def SetData(self, values):
+        """Allows setting of all values at once. Requires a single value or
+        a iterable object."""
+        if not hasattr(values, "__iter__"):
+            values = (values,)
+        iup = self.SMProperty.GetImmediateUpdate()
+        self.SMProperty.SetImmediateUpdate(False)
+        if not self.GetRepeatable() and len(values) != self.GetNumberOfElements():
+            raise RuntimeError("This property requires %d values." % self.GetNumberOfElements())
+        if self.GetRepeatable():
+            # Clean up first
+            self.SMProperty.SetNumberOfElements(0)
+        idx = 0
+        for val in values:
+            self.SMProperty.SetElement(idx, self.ConvertValue(val))
+            idx += 1
+        self.SMProperty.SetImmediateUpdate(iup)
+        self._UpdateProperty()
+
+    def Clear(self):
+        "Removes all elements."
+        self.SMProperty().SetNumberOfElements(0)
+        self._UpdateProperty()
+
+class ColorArrayProperty(VectorProperty):
+    """This subclass of VectorProperty handles setting of the array to
+    color by. It handles attribute type as well as well array name."""
+
+    def GetAvailable(self):
+        """"Returns the list of available arrays as (attribute type, array name
+        tuples."""
+        arrays = []
+        for a in self.Proxy.Input.PointData:
+            arrays.append(('POINT_DATA', a.GetName()))
+        for a in self.Proxy.Input.CellData:
+            arrays.append(('CELL_DATA', a.GetName()))
+        return arrays
+
+    def SetData(self, value):
+        """Overwritten to enable setting attribute type (the ColorAttributeType
+        property and the array name. The argument should be the array name
+        (in which case the first appropriate attribute type is picked) or
+        a tuple of attribute type and array name."""
+        if isinstance(value, tuple) and len(value) == 2:
+            att = value[0]
+            arr = value[1]
+        elif isinstance(value, str):
+            att = None
+            arr = value
+        else:
+            raise ValueError("Expected a tuple of 2 values or a string.")
+
+        if not arr:
+            self.SMProperty.SetElement(0, '')
+            self._UpdateProperty()
+            return
+
+        found = False
+        for a in self.Available:
+            if a[1] == arr and (not att or att == a[0]):
+                att = a[0]
+                found = True
+                break
+
+        if  not found:
+            raise ValueError("Could not locate array %s in the input." % arr)
+
+        catt = self.Proxy.GetProperty("ColorAttributeType")
+        catt.SetData(att)
+        self.SMProperty.SetElement(0, arr)
+        self._UpdateProperty()
+
+    Available = property(GetAvailable, None, None, \
+        "This read-only property returns the list of arrays that can be colored by.")
+
+
+class EnumerationProperty(VectorProperty):
+    """"Subclass of VectorProperty that is applicable for enumeration type
+    properties."""
+
+    def GetElement(self, index):
+        """Returns the text for the given element if available. Returns
+        the numerical values otherwise."""
+        val = self.SMProperty.GetElement(index)
+        domain = self.SMProperty.GetDomain("enum")
+        for i in range(domain.GetNumberOfEntries()):
+            if domain.GetEntryValue(i) == val:
+                return domain.GetEntryText(i)
+        return val
+
+    def ConvertValue(self, value):
+        """Converts value to type suitable for vtSMProperty::SetElement()"""
+        if type(value) == str:
+            domain = self.SMProperty.GetDomain("enum")
+            if domain.HasEntryText(value):
+                return domain.GetEntryValueForText(value)
+            else:
+                raise ValueError("%s is not a valid value." % value)
+        return VectorProperty.ConvertValue(self, value)
+
+    def GetAvailable(self):
+        "Returns the list of available values for the property."
+        retVal = []
+        domain = self.SMProperty.GetDomain("enum")
+        for i in range(domain.GetNumberOfEntries()):
+            retVal.append(domain.GetEntryText(i))
+        return retVal
+
+    Available = property(GetAvailable, None, None, \
+        "This read-only property contains the list of values that can be applied to this property.")
+
+
+class FileNameProperty(VectorProperty):
+    """Property to set/get one or more file names.
+    This property updates the pipeline information everytime its value changes.
+    This is used to keep the array lists up to date."""
+
+    def _UpdateProperty(self):
+        "Pushes the value of this property to the server."
+        VectorProperty._UpdateProperty(self)
+        self.Proxy.FileNameChanged()
+
+class ArraySelectionProperty(VectorProperty):
+    "Property to select an array to be processed by a filter."
+
+    def GetAssociation(self):
+        val = self.GetElement(3)
+        if val == "":
+            return None
+        for key, value in ASSOCIATIONS.iteritems():
+            if value == int(val):
+                return key
+
+        return None
+
+    def GetArrayName(self):
+        return self.GetElement(4)
+
+    def __len__(self):
+        """Returns the number of elements."""
+        return 2
+
+    def __setitem__(self, idx, value):
+        raise RuntimeError, "This property cannot be accessed using __setitem__"
+
+    def __getitem__(self, idx):
+        """Returns attribute type for index 0, array name for index 1"""
+        if isinstance(idx, slice):
+            indices = idx.indices(len(self))
+            retVal = []
+            for i in range(*indices):
+                if i >= 2 or i < 0:
+                    raise IndexError
+                if i == 0:
+                    retVal.append(self.GetAssociation())
+                else:
+                    retVal.append(self.GetArrayName())
+            return retVal
+        elif idx >= 2 or idx < 0:
+            raise IndexError
+
+        if i == 0:
+            return self.GetAssociation()
+        else:
+            return self.GetArrayName()
+
+    def SetData(self, values):
+        """Allows setting of all values at once. Requires a single value,
+        a tuple or list."""
+        if not isinstance(values, tuple) and \
+           not isinstance(values, list):
+            values = (values,)
+        if len(values) == 1:
+            self.SMProperty.SetElement(4, values[0])
+        elif len(values) == 2:
+            if isinstance(values[0], str):
+                val = str(ASSOCIATIONS[values[0]])
+            self.SMProperty.SetElement(3,  str(val))
+            self.SMProperty.SetElement(4, values[1])
+        else:
+            raise RuntimeError, "Expected 1 or 2 values."
+        self._UpdateProperty()
+
+    def UpdateDefault(self):
+        "Helper method to set default values."
+        if self.SMProperty.GetNumberOfElements() != 5:
+            return
+        if self.GetElement(4) != '' or \
+            self.GetElement(3) != '':
+            return
+
+        for i in range(0,3):
+            if self.GetElement(i) == '':
+                self.SMProperty.SetElement(i, '0')
+        al = self.SMProperty.GetDomain("array_list")
+        al.Update(self.SMProperty)
+        al.SetDefaultValues(self.SMProperty)
+
+class ArrayListProperty(VectorProperty):
+    """This property provides a simpler interface for selecting arrays.
+    Simply assign a list of arrays that should be loaded by the reader.
+    Use the Available property to get a list of available arrays."""
+
+    def __init__(self, proxy, smproperty):
+        VectorProperty.__init__(self, proxy, smproperty)
+        self.__arrays = []
+
+    def GetAvailable(self):
+        "Returns the list of available arrays"
+        dm = self.GetDomain("array_list")
+        retVal = []
+        for i in range(dm.GetNumberOfStrings()):
+            retVal.append(dm.GetString(i))
+        return retVal
+
+    Available = property(GetAvailable, None, None, \
+        "This read-only property contains the list of items that can be read by a reader.")
+
+    def SelectAll(self):
+        "Selects all arrays."
+        self.SetData(self.Available)
+
+    def DeselectAll(self):
+        "Deselects all arrays."
+        self.SetData([])
+
+    def __iter__(self):
+        """Implementation of the sequence API"""
+        return GenericIterator(self)
+
+    def __len__(self):
+        """Returns the number of elements."""
+        return len(self.GetData())
+
+    def __setitem__(self, idx, value):
+      """Given a list or tuple of values, sets a slice of values [min, max)"""
+      self.GetData()
+      if isinstance(idx, slice):
+          indices = idx.indices(len(self))
+          for i, j in zip(range(*indices), value):
+              self.__arrays[i] = j
+          self.SetData(self.__arrays)
+      elif idx >= len(self) or idx < 0:
+          raise IndexError
+      else:
+          self.__arrays[idx] = self.ConvertValue(value)
+          self.SetData(self.__arrays)
+
+    def __getitem__(self, idx):
+      """Returns the range [min, max) of elements. Raises an IndexError
+      exception if an argument is out of bounds."""
+      self.GetData()
+      if isinstance(idx, slice):
+          indices = idx.indices(len(self))
+          retVal = []
+          for i in range(*indices):
+              retVal.append(self.__arrays[i])
+          return retVal
+      elif idx >= len(self) or idx < 0:
+          raise IndexError
+      return self.__arrays[idx]
+
+    def SetData(self, values):
+        """Allows setting of all values at once. Requires a single value,
+        a tuple or list."""
+        # Clean up first
+        iup = self.SMProperty.GetImmediateUpdate()
+        self.SMProperty.SetImmediateUpdate(False)
+        # Clean up first
+        self.SMProperty.SetNumberOfElements(0)
+        if not isinstance(values, tuple) and \
+           not isinstance(values, list):
+            values = (values,)
+        fullvalues = []
+        for i in range(len(values)):
+            val = self.ConvertValue(values[i])
+            fullvalues.append(val)
+            fullvalues.append('1')
+        for array in self.Available:
+            if not values.__contains__(array):
+                fullvalues.append(array)
+                fullvalues.append('0')
+        i = 0
+        for value in fullvalues:
+            self.SMProperty.SetElement(i, value)
+            i += 1
+
+        self._UpdateProperty()
+        self.SMProperty.SetImmediateUpdate(iup)
+
+    def GetData(self):
+        "Returns all elements as a list."
+        property = self.SMProperty
+        nElems = property.GetNumberOfElements()
+        if nElems%2 != 0:
+            raise ValueError, "The SMProperty with XML label '%s' has a size that is not a multiple of 2." % property.GetXMLLabel()
+        self.__arrays = []
+        for i in range(0, nElems, 2):
+            if self.GetElement(i+1) != '0':
+                self.__arrays.append(self.GetElement(i))
+        return list(self.__arrays)
+
+class ProxyProperty(Property):
+    """A ProxyProperty provides access to one or more proxies. You can use
+    a slice to get one or more property values:
+    > proxy = property[2]
+    or
+    > proxies = property[0:5:2]
+    You can use a slice to set one or more property values:
+    > property[2] = proxy
+    or
+    > property[1:3] = (proxy1, proxy2)
+    You can also append and delete:
+    > property.append(proxy)
+    and
+    > del property[1:2]
+
+    You can also remove all elements with Clear().
+
+    Note that some properties expect only 1 proxy and will complain if
+    you set the number of values to be something else.
+    """
+    def __init__(self, proxy, smproperty):
+        """Default constructor.  Stores a reference to the proxy.  Also looks
+        at domains to find valid values."""
+        Property.__init__(self, proxy, smproperty)
+        # Check to see if there is a proxy list domain and, if so,
+        # initialize ourself. (Should this go in ProxyProperty?)
+        listdomain = self.GetDomain('proxy_list')
+        if listdomain:
+            if listdomain.GetClassName() != 'vtkSMProxyListDomain':
+                raise ValueError, "Found a 'proxy_list' domain on an InputProperty that is not a ProxyListDomain."
+            pm = ProxyManager()
+            group = "pq_helper_proxies." + proxy.GetSelfIDAsString()
+            if listdomain.GetNumberOfProxies() == 0:
+                for i in xrange(listdomain.GetNumberOfProxyTypes()):
+                    igroup = listdomain.GetProxyGroup(i)
+                    name = listdomain.GetProxyName(i)
+                    iproxy = CreateProxy(igroup, name)
+                    listdomain.AddProxy(iproxy)
+                    pm.RegisterProxy(group, proxy.GetPropertyName(smproperty), iproxy)
+                listdomain.SetDefaultValues(self.SMProperty)
+
+    def GetAvailable(self):
+        """If this proxy has a list domain, then this function returns the
+        strings you can use to select from the domain.  If there is no such
+        list domain, the returned list is empty."""
+        listdomain = self.GetDomain('proxy_list')
+        retval = []
+        if listdomain:
+            for i in xrange(listdomain.GetNumberOfProxies()):
+                proxy = listdomain.GetProxy(i)
+                retval.append(proxy.GetXMLLabel())
+        return retval
+
+    Available = property(GetAvailable, None, None,
+                         """This read only property is a list of strings you can
+                         use to select from the list domain.  If there is no
+                         such list domain, the array is empty.""")
+
+    def __iter__(self):
+        """Implementation of the sequence API"""
+        return GenericIterator(self)
+
+    def __len__(self):
+        """Returns the number of elements."""
+        return self.SMProperty.GetNumberOfProxies()
+
+    def remove(self, proxy):
+        """Removes the first occurence of the proxy from the property."""
+        self.SMProperty.RemoveProxy(proxy.SMProxy)
+        self._UpdateProperty()
+        
+    def __setitem__(self, idx, value):
+      """Given a list or tuple of values, sets a slice of values [min, max)"""
+      if isinstance(idx, slice):
+        indices = idx.indices(len(self))
+        for i, j in zip(range(*indices), value):
+          self.SMProperty.SetProxy(i, j.SMProxy)
+        self._UpdateProperty()
+      elif idx >= len(self) or idx < 0:
+        raise IndexError
+      else:
+        self.SMProperty.SetProxy(idx, value.SMProxy)
+        self._UpdateProperty()
+
+    def __delitem__(self,idx):
+      """Removes the element idx"""
+      if isinstance(idx, slice):
+        indices = idx.indices(len(self))
+        # Collect the elements to delete to a new list first.
+        # Otherwise indices are screwed up during the actual
+        # remove loop.
+        toremove = []
+        for i in range(*indices):
+          toremove.append(self[i])
+        for i in toremove:
+          self.SMProperty.RemoveProxy(i.SMProxy)
+        self._UpdateProperty()
+      elif idx >= len(self) or idx < 0:
+        raise IndexError
+      else:
+        self.SMProperty.RemoveProxy(self[idx].SMProxy)
+        self._UpdateProperty()
+
+    def __getitem__(self, idx):
+      """Returns the range [min, max) of elements. Raises an IndexError
+      exception if an argument is out of bounds."""
+      if isinstance(idx, slice):
+        indices = idx.indices(len(self))
+        retVal = []
+        for i in range(*indices):
+          retVal.append(_getPyProxy(self.SMProperty.GetProxy(i)))
+        return retVal
+      elif idx >= len(self) or idx < 0:
+        raise IndexError
+      return _getPyProxy(self.SMProperty.GetProxy(idx))
+
+    def __getattr__(self, name):
+        "Unknown attribute requests get forwarded to SMProperty."
+        return getattr(self.SMProperty, name)
+
+    def index(self, proxy):
+        idx = 0
+        for px in self:
+            ## VSV: ==
+            if proxy.IsSame(px):
+                return idx
+            idx += 1
+        raise ValueError("proxy is not in the list.")
+
+    def append(self, proxy):
+        "Appends the given proxy to the property values."
+        self.SMProperty.AddProxy(proxy.SMProxy)
+        self._UpdateProperty()
+
+    def GetData(self):
+        "Returns all elements as either a list or a single value."
+        property = self.SMProperty
+        if property.GetRepeatable() or property.GetNumberOfProxies() > 1:
+            return self[0:len(self)]
+        else:
+            if property.GetNumberOfProxies() > 0:
+                return _getPyProxy(property.GetProxy(0))
+        return None
+
+    def SetData(self, values):
+        """Allows setting of all values at once. Requires a single value,
+        a tuple or list."""
+        if isinstance(values, str):
+            position = -1
+            try:
+                position = self.Available.index(values)
+            except:
+                raise ValueError, values + " is not a valid object in the domain."
+            values = self.GetDomain('proxy_list').GetProxy(position)
+        if not isinstance(values, tuple) and \
+           not isinstance(values, list):
+            values = (values,)
+        self.SMProperty.RemoveAllProxies()
+        for value in values:
+            if isinstance(value, Proxy):
+                value_proxy = value.SMProxy
+            else:
+                value_proxy = value
+            self.SMProperty.AddProxy(value_proxy)
+        self._UpdateProperty()
+
+    def Clear(self):
+        "Removes all elements."
+        self.SMProperty.RemoveAllProxies()
+        self._UpdateProperty()
+
+class InputProperty(ProxyProperty):
+    """An InputProperty allows making pipeline connections. You can set either
+    a source proxy or an OutputProperty to an input property:
+
+    > property[0] = proxy
+    or
+    > property[0] = OuputPort(proxy, 1)
+
+    > property.append(proxy)
+    or
+    > property.append(OutputPort(proxy, 0))
+    """
+    def __setitem__(self, idx, value):
+      """Given a list or tuple of values, sets a slice of values [min, max)"""
+      if isinstance(idx, slice):
+        indices = idx.indices(len(self))
+        for i, j in zip(range(*indices), value):
+          op = value[i-min]
+          self.SMProperty.SetInputConnection(i, op.SMProxy, op.Port)
+        self._UpdateProperty()
+      elif idx >= len(self) or idx < 0:
+        raise IndexError
+      else:
+        self.SMProperty.SetInputConnection(idx, value.SMProxy, value.Port)
+        self._UpdateProperty()
+
+    def __getitem__(self, idx):
+      """Returns the range [min, max) of elements. Raises an IndexError
+      exception if an argument is out of bounds."""
+      if isinstance(idx, slice):
+        indices = idx.indices(len(self))
+        retVal = []
+        for i in range(*indices):
+            port = None
+            if self.SMProperty.GetProxy(i):
+                port = OutputPort(_getPyProxy(self.SMProperty.GetProxy(i)),\
+                                  self.SMProperty.GetOutputPortForConnection(i))
+            retVal.append(port)
+        return retVal
+      elif idx >= len(self) or idx < 0:
+        raise IndexError
+      return OutputPort(_getPyProxy(self.SMProperty.GetProxy(idx)),\
+                        self.SMProperty.GetOutputPortForConnection(idx))
+
+    def append(self, value):
+        """Appends the given proxy to the property values.
+        Accepts Proxy or OutputPort objects."""
+        self.SMProperty.AddInputConnection(value.SMProxy, value.Port)
+        self._UpdateProperty()
+
+    def GetData(self):
+        """Returns all elements as either a list of OutputPort objects or
+        a single OutputPort object."""
+        property = self.SMProperty
+        if property.GetRepeatable() or property.GetNumberOfProxies() > 1:
+            return self[0:len(self)]
+        else:
+            if property.GetNumberOfProxies() > 0:
+                return OutputPort(_getPyProxy(property.GetProxy(0)),\
+                                  self.SMProperty.GetOutputPortForConnection(0))
+        return None
+
+    def SetData(self, values):
+        """Allows setting of all values at once. Requires a single value,
+        a tuple or list. Accepts Proxy or OutputPort objects."""
+        if isinstance(values, str):
+            ProxyProperty.SetData(self, values)
+            return
+        if not isinstance(values, tuple) and \
+           not isinstance(values, list):
+            values = (values,)
+        self.SMProperty.RemoveAllProxies()
+        for value in values:
+            if value:
+                self.SMProperty.AddInputConnection(value.SMProxy, value.Port)
+        self._UpdateProperty()
+
+    def _UpdateProperty(self):
+        "Pushes the value of this property to the server."
+        ProxyProperty._UpdateProperty(self)
+        iter = PropertyIterator(self.Proxy)
+        for prop in iter:
+            if isinstance(prop, ArraySelectionProperty):
+                prop.UpdateDefault()
+
+
+class DataInformation(object):
+    """DataInformation is a contained for meta-data associated with an
+    output data.
+
+    DataInformation is a python wrapper around a vtkPVDataInformation.
+    In addition to proving all methods of a vtkPVDataInformation, it provides
+    a few convenience methods.
+
+    Please note that some of the methods accessible through the DataInformation
+    class are not listed by help() because the DataInformation objects forward
+    unresolved attributes to the underlying object. To get the full list,
+    see also dir(proxy.DataInformation).
+    See also the doxygen based documentation of the vtkPVDataInformation C++
+    class.
+    """
+    def __init__(self, dataInformation, proxy, idx):
+        """Default constructor. Requires a vtkPVDataInformation, a source proxy
+        and an output port id."""
+        self.DataInformation = dataInformation
+        self.Proxy = proxy
+        self.Idx = idx
+
+    def Update(self):
+        """****Deprecated**** There is no reason anymore to use this method
+        explicitly, it is called automatically when one gets any value from the
+        data information object.
+        Update the data information if necessary. Note that this
+        does not cause execution of the underlying object. In certain
+        cases, you may have to call UpdatePipeline() on the proxy."""
+        if self.Proxy:
+            self.Proxy.GetDataInformation(self.Idx)
+
+    def GetDataSetType(self):
+        """Returns the dataset type as defined in vtkDataObjectTypes."""
+        self.Update()
+        if not self.DataInformation:
+            raise RuntimeError, "No data information is available"
+        if self.DataInformation.GetCompositeDataSetType() > -1:
+            return self.DataInformation.GetCompositeDataSetType()
+        return self.DataInformation.GetDataSetType()
+
+    def GetDataSetTypeAsString(self):
+        """Returns the dataset type as a user-friendly string. This is
+        not the same as the enumaration used by VTK"""
+        return vtkDataObjectTypes.GetClassNameFromTypeId(self.GetDataSetType())
+
+    def __getattr__(self, name):
+        """Forwards unknown attribute requests to the underlying
+        vtkPVInformation."""
+        if not self.DataInformation:
+            raise AttributeError("class has no attribute %s" % name)
+            return None
+        self.Update()
+        return getattr(self.DataInformation, name)
+
+class ArrayInformation(object):
+    """Meta-information associated with an array. Use the Name
+    attribute to get the array name.
+
+    Please note that some of the methods accessible through the ArrayInformation
+    class are not listed by help() because the ArrayInformation objects forward
+    unresolved attributes to the underlying object.
+    See the doxygen based documentation of the vtkPVArrayInformation C++
+    class for a full list.
+    """
+    def __init__(self, proxy, field, name):
+        self.Proxy = proxy
+        self.FieldData = field
+        self.Name = name
+
+    def __getattr__(self, name):
+        """Forward unknown methods to vtkPVArrayInformation"""
+        array = self.FieldData.GetFieldData().GetArrayInformation(self.Name)
+        if not array: return None
+        return getattr(array, name)
+
+    def __repr__(self):
+        """Returns a user-friendly representation string."""
+        return "Array: " + self.Name
+
+    def GetRange(self, component=0):
+        """Given a component, returns its value range as a tuple of 2 values."""
+        array = self.FieldData.GetFieldData().GetArrayInformation(self.Name)
+        range = array.GetComponentRange(component)
+        return (range[0], range[1])
+
+
+class FieldDataInformationIterator(object):
+    """Iterator for FieldDataInformation"""
+
+    def __init__(self, info, items=False):
+        self.FieldDataInformation = info
+        self.index = 0
+        self.items = items
+
+    def __iter__(self):
+        return self
+
+    def next(self):
+        if self.index >= self.FieldDataInformation.GetNumberOfArrays():
+            raise StopIteration
+
+        self.index += 1
+        ai = self.FieldDataInformation[self.index-1]
+        if self.items:
+            return (ai.GetName(), ai)
+        else:
+            return ai
+
+
+class FieldDataInformation(object):
+    """Meta-data for a field of an output object (point data, cell data etc...).
+    Provides easy access to the arrays using the slice interface:
+    > narrays = len(field_info)
+    > for i in range(narrays):
+    >   array_info = field_info[i]
+
+    Full slice interface is supported:
+    > arrays = field_info[0:5:3]
+    where arrays is a list.
+
+    Array access by name is also possible:
+    > array_info = field_info['Temperature']
+
+    The number of arrays can also be accessed using the NumberOfArrays
+    property.
+    """
+    def __init__(self, proxy, idx, field):
+        self.Proxy = proxy
+        self.OutputPort = idx
+        self.FieldData = field
+
+    def GetFieldData(self):
+        """Convenience method to get the underlying
+        vtkPVDataSetAttributesInformation"""
+        return getattr(self.Proxy.GetDataInformation(self.OutputPort), "Get%sInformation" % self.FieldData)()
+
+    def GetNumberOfArrays(self):
+        """Returns the number of arrays."""
+        self.Proxy.UpdatePipeline()
+        return self.GetFieldData().GetNumberOfArrays()
+
+    def GetArray(self, idx):
+        """Given an index or a string, returns an array information.
+        Raises IndexError if the index is out of bounds."""
+        self.Proxy.UpdatePipeline()
+        if not self.GetFieldData().GetArrayInformation(idx):
+            return None
+        if isinstance(idx, str):
+            return ArrayInformation(self.Proxy, self, idx)
+        elif idx >= len(self) or idx < 0:
+            raise IndexError
+        return ArrayInformation(self.Proxy, self, self.GetFieldData().GetArrayInformation(idx).GetName())
+
+    def __len__(self):
+        """Returns the number of arrays."""
+        return self.GetNumberOfArrays()
+
+    def __getitem__(self, idx):
+        """Implements the [] operator. Accepts an array name."""
+        if isinstance(idx, slice):
+            indices = idx.indices(self.GetNumberOfArrays())
+            retVal = []
+            for i in range(*indices):
+                retVal.append(self.GetArray(i))
+            return retVal
+        return self.GetArray(idx)
+
+    def keys(self):
+        """Implementation of the dictionary API"""
+        kys = []
+        narrays = self.GetNumberOfArrays()
+        for i in range(narrays):
+            kys.append(self.GetArray(i).GetName())
+        return kys
+
+    def values(self):
+        """Implementation of the dictionary API"""
+        vals = []
+        narrays = self.GetNumberOfArrays()
+        for i in range(narrays):
+            vals.append(self.GetArray(i))
+        return vals
+
+    def iteritems(self):
+        """Implementation of the dictionary API"""
+        return FieldDataInformationIterator(self, True)
+
+    def items(self):
+        """Implementation of the dictionary API"""
+        itms = []
+        narrays = self.GetNumberOfArrays()
+        for i in range(narrays):
+            ai = self.GetArray(i)
+            itms.append((ai.GetName(), ai))
+        return itms
+
+    def has_key(self, key):
+        """Implementation of the dictionary API"""
+        if self.GetArray(key):
+            return True
+        return False
+
+    def __iter__(self):
+        """Implementation of the dictionary API"""
+        return FieldDataInformationIterator(self)
+
+    def __getattr__(self, name):
+        """Forwards unknown attributes to the underlying
+        vtkPVDataSetAttributesInformation"""
+        array = self.GetArray(name)
+        if array: return array
+        raise AttributeError("class has no attribute %s" % name)
+        return None
+
+    NumberOfArrays = property(GetNumberOfArrays, None, None, "Returns the number of arrays.")
+
+def OutputPort(proxy, outputPort=0):
+    if not Proxy:
+        return None
+    if isinstance(outputPort, str):
+        outputPort = proxy.GetOutputPortIndex(outputPort)
+    if outputPort >= proxy.GetNumberOfOutputPorts():
+        return None
+    if proxy.Port == outputPort:
+        return proxy
+    newinstance = _getPyProxy(proxy.SMProxy, outputPort)
+    newinstance.Port = outputPort
+    newinstance._Proxy__Properties = proxy._Proxy__Properties
+    return newinstance
+
+class ProxyManager(object):
+    """When running scripts from the python shell in the ParaView application,
+    registering proxies with the proxy manager is the ony mechanism to
+    notify the graphical user interface (GUI) that a proxy
+    exists. Therefore, unless a proxy is registered, it will not show up in
+    the user interface. Also, the proxy manager is the only way to get
+    access to proxies created using the GUI. Proxies created using the GUI
+    are automatically registered under an appropriate group (sources,
+    filters, representations and views). To get access to these objects,
+    you can use proxyManager.GetProxy(group, name). The name is the same
+    as the name shown in the pipeline browser.
+
+    This class is a python wrapper for vtkSMProxyManager. Note that the
+    underlying vtkSMProxyManager is a singleton. All instances of this
+    class wil refer to the same object. In addition to all methods provided by
+    vtkSMProxyManager (all unknown attribute requests are forwarded
+    to the vtkSMProxyManager), this class provides several convenience
+    methods.
+
+    Please note that some of the methods accessible through the ProxyManager
+    class are not listed by help() because the ProxyManager objects forwards
+    unresolved attributes to the underlying object. To get the full list,
+    see also dir(proxy.SMProxyManager). See also the doxygen based documentation
+    of the vtkSMProxyManager C++ class.
+    """
+
+    def __init__(self):
+        """Constructor. Assigned self.SMProxyManager to
+        vtkSMObject.GetPropertyManager()."""
+        self.SMProxyManager = vtkSMObject.GetProxyManager()
+
+    def RegisterProxy(self, group, name, aProxy):
+        """Registers a proxy (either SMProxy or proxy) with the
+        server manager"""
+        if isinstance(aProxy, Proxy):
+            self.SMProxyManager.RegisterProxy(group, name, aProxy.SMProxy)
+        else:
+            self.SMProxyManager.RegisterProxy(group, name, aProxy)
+
+    def NewProxy(self, group, name):
+        """Creates a new proxy of given group and name and returns an SMProxy.
+        Note that this is a server manager object. You should normally create
+        proxies using the class objects. For example:
+        obj = servermanager.sources.SphereSource()"""
+        if not self.SMProxyManager:
+            return None
+        aProxy = self.SMProxyManager.NewProxy(group, name)
+        if not aProxy:
+            return None
+        aProxy.UnRegister(None)
+        return aProxy
+
+    def GetProxy(self, group, name):
+        """Returns a Proxy registered under a group and name"""
+        if not self.SMProxyManager:
+            return None
+        aProxy = self.SMProxyManager.GetProxy(group, name)
+        if not aProxy:
+            return None
+        return _getPyProxy(aProxy)
+
+    def GetPrototypeProxy(self, group, name):
+        """Returns a prototype proxy given a group and name. This is an
+        SMProxy. This is a low-level method. You should not normally
+        have to call it."""
+        if not self.SMProxyManager:
+            return None
+        aProxy = self.SMProxyManager.GetPrototypeProxy(group, name)
+        if not aProxy:
+            return None
+        return aProxy
+
+    def GetProxiesOnConnection(self, connection):
+        """Returns a map of proxies registered with the proxy manager
+           on the particular connection."""
+        proxy_groups = {}
+        iter = self.NewConnectionIterator(connection)
+        for proxy in iter:
+            if not proxy_groups.has_key(iter.GetGroup()):
+                proxy_groups[iter.GetGroup()] = {}
+            group = proxy_groups[iter.GetGroup()]
+            group[(iter.GetKey(), proxy.GetSelfIDAsString())] = proxy
+        return proxy_groups
+
+    def GetProxiesInGroup(self, groupname, connection=None):
+        """Returns a map of proxies in a particular group.
+         If connection is not None, then only those proxies
+         in the group that are on the particular connection
+         are returned.
+        """
+        proxies = {}
+        iter = self.NewGroupIterator(groupname)
+        for aProxy in iter:
+            proxies[(iter.GetKey(), aProxy.GetSelfIDAsString())] = aProxy
+        return proxies
+
+    def UnRegisterProxy(self, groupname, proxyname, aProxy):
+        """Unregisters a proxy."""
+        if not self.SMProxyManager:
+            return
+        if aProxy != None and isinstance(aProxy,Proxy):
+            aProxy = aProxy.SMProxy
+        if aProxy:
+            self.SMProxyManager.UnRegisterProxy(groupname, proxyname, aProxy)
+
+    def GetProxies(self, groupname, proxyname):
+        """Returns all proxies registered under the given group with the
+        given name. Note that it is possible to register more than one
+        proxy with the same name in the same group. Because the proxies
+        are different, there is no conflict. Use this method instead of
+        GetProxy() if you know that there are more than one proxy registered
+        with this name."""
+        if not self.SMProxyManager:
+            return []
+        collection = vtkCollection()
+        result = []
+        self.SMProxyManager.GetProxies(groupname, proxyname, collection)
+        for i in range(0, collection.GetNumberOfItems()):
+            aProxy = _getPyProxy(collection.GetItemAsObject(i))
+            if aProxy:
+                result.append(aProxy)
+
+        return result
+
+    def __iter__(self):
+        """Returns a new ProxyIterator."""
+        iter = ProxyIterator()
+        if ActiveConnection:
+            iter.SetConnectionID(ActiveConnection.ID)
+        iter.Begin()
+        return iter
+
+    def NewGroupIterator(self, group_name, connection=None):
+        """Returns a ProxyIterator for a group. The resulting object
+        can be used to traverse the proxies that are in the given
+        group."""
+        iter = self.__iter__()
+        if not connection:
+            connection = ActiveConnection
+        if connection:
+            iter.SetConnectionID(connection.ID)
+        iter.SetModeToOneGroup()
+        iter.Begin(group_name)
+        return iter
+
+    def NewConnectionIterator(self, connection=None):
+        """Returns a ProxyIterator for a given connection. This can be
+        used to travers ALL proxies managed by the proxy manager."""
+        iter = self.__iter__()
+        if not connection:
+            connection = ActiveConnection
+        if connection:
+            iter.SetConnectionID(connection.ID)
+        iter.Begin()
+        return iter
+
+    def NewDefinitionIterator(self, groupname=None):
+        """Returns an iterator that can be used to iterate over
+           all groups and types of proxies that the proxy manager
+           can create."""
+        iter = ProxyDefinitionIterator()
+        if groupname != None:
+            iter.SetModeToOneGroup()
+            iter.Begin(groupname)
+        return iter
+
+    def __ConvertArgumentsAndCall(self, *args):
+      newArgs = []
+      for arg in args:
+          if issubclass(type(arg), Proxy) or isinstance(arg, Proxy):
+              newArgs.append(arg.SMProxy)
+          else:
+              newArgs.append(arg)
+      func = getattr(self.SMProxyManager, self.__LastAttrName)
+      retVal = func(*newArgs)
+      if type(retVal) is type(self.SMProxyManager) and retVal.IsA("vtkSMProxy"):
+          return _getPyProxy(retVal)
+      else:
+          return retVal
+
+    def __getattr__(self, name):
+        """Returns attribute from the ProxyManager"""
+        try:
+            pmAttr = getattr(self.SMProxyManager, name)
+            self.__LastAttrName = name
+            return self.__ConvertArgumentsAndCall
+        except:
+            pass
+        return getattr(self.SMProxyManager, name)
+
+
+class PropertyIterator(object):
+    """Wrapper for a vtkSMPropertyIterator class to satisfy
+       the python iterator protocol. Note that the list of
+       properties can also be obtained from the class object's
+       dictionary.
+       See the doxygen documentation for vtkSMPropertyIterator C++
+       class for details.
+       """
+
+    def __init__(self, aProxy):
+        self.SMIterator = aProxy.NewPropertyIterator()
+        if self.SMIterator:
+            self.SMIterator.UnRegister(None)
+            self.SMIterator.Begin()
+        self.Key = None
+        self.PropertyLabel = None
+        self.Proxy = aProxy
+
+    def __iter__(self):
+        return self
+
+    def next(self):
+        if not self.SMIterator:
+            raise StopIteration
+
+        if self.SMIterator.IsAtEnd():
+            self.Key = None
+            raise StopIteration
+        self.Key = self.SMIterator.GetKey()
+        self.PropertyLabel = self.SMIterator.GetPropertyLabel()
+        self.SMIterator.Next()
+        return self.Proxy.GetProperty(self.Key)
+
+    def GetProxy(self):
+        """Returns the proxy for the property last returned by the call to
+        'next()'"""
+        return self.Proxy
+
+    def GetKey(self):
+        """Returns the key for the property last returned by the call to
+        'next()' """
+        return self.Key
+
+    def GetProperty(self):
+        """Returns the property last returned by the call to 'next()' """
+        return self.Proxy.GetProperty(self.Key)
+
+    def __getattr__(self, name):
+        """returns attributes from the vtkSMProxyIterator."""
+        return getattr(self.SMIterator, name)
+
+class ProxyDefinitionIterator(object):
+    """Wrapper for a vtkSMProxyDefinitionIterator class to satisfy
+       the python iterator protocol.
+       See the doxygen documentation of the vtkSMProxyDefinitionIterator
+       C++ class for more information."""
+    def __init__(self):
+        self.SMIterator = vtkSMProxyDefinitionIterator()
+        self.Group = None
+        self.Key = None
+
+    def __iter__(self):
+        return self
+
+    def next(self):
+        if self.SMIterator.IsAtEnd():
+            self.Group = None
+            self.Key = None
+            raise StopIteration
+        self.Group = self.SMIterator.GetGroup()
+        self.Key = self.SMIterator.GetKey()
+        self.SMIterator.Next()
+        return {"group": self.Group, "key":self.Key }
+
+    def GetKey(self):
+        """Returns the key for the proxy definition last returned by the call
+        to 'next()' """
+        return self.Key
+
+    def GetGroup(self):
+        """Returns the group for the proxy definition last returned by the
+        call to 'next()' """
+        return self.Group
+
+    def __getattr__(self, name):
+        """returns attributes from the vtkSMProxyDefinitionIterator."""
+        return getattr(self.SMIterator, name)
+
+
+class ProxyIterator(object):
+    """Wrapper for a vtkSMProxyIterator class to satisfy the
+     python iterator protocol.
+     See the doxygen documentation of vtkSMProxyIterator C++ class for
+     more information.
+     """
+    def __init__(self):
+        self.SMIterator = vtkSMProxyIterator()
+        self.SMIterator.Begin()
+        self.AProxy = None
+        self.Group = None
+        self.Key = None
+
+    def __iter__(self):
+        return self
+
+    def next(self):
+        if self.SMIterator.IsAtEnd():
+            self.AProxy = None
+            self.Group = None
+            self.Key = None
+            raise StopIteration
+            return None
+        self.AProxy = _getPyProxy(self.SMIterator.GetProxy())
+        self.Group = self.SMIterator.GetGroup()
+        self.Key = self.SMIterator.GetKey()
+        self.SMIterator.Next()
+        return self.AProxy
+
+    def GetProxy(self):
+        """Returns the proxy last returned by the call to 'next()'"""
+        return self.AProxy
+
+    def GetKey(self):
+        """Returns the key for the proxy last returned by the call to
+        'next()' """
+        return self.Key
+
+    def GetGroup(self):
+        """Returns the group for the proxy last returned by the call to
+        'next()' """
+        return self.Group
+
+    def __getattr__(self, name):
+        """returns attributes from the vtkSMProxyIterator."""
+        return getattr(self.SMIterator, name)
+
+class Connection(object):
+    """
+      This is a python representation for a connection.
+    """
+    def __init__(self, connectionId):
+        """Default constructor. Creates a Connection with the given
+        ID, all other data members initialized to None."""
+        self.ID = connectionId
+        self.Hostname = None
+        self.Port = None
+        self.RSHostname = None
+        self.RSPort = None
+        self.Reverse = False
+        return
+
+    def __eq__(self, other):
+        "Returns true if the connection ids are the same."
+        return self.ID == other.ID
+
+    def SetHost(self, ds_host=None, ds_port=None, rs_host=None, rs_port=None,
+      reverse=False):
+        """
+          Set the hostname of a given connection. Used by Connect().
+          If all args are None, it's assumed to be a built-in connection i.e.
+          connection scheme = builtin.
+        """
+        self.Hostname = ds_host
+        self.Port = ds_port
+        self.RSHostname = rs_host
+        self.RSPort = rs_port
+        self.Reversed = reverse
+        return
+
+    def __repr__(self):
+        """User friendly string representation"""
+        if not self.Hostname:
+           return "Connection (builtin[%d]:)" % self.ID
+        if not self.RSHostname:
+            return "Connection (%s:%d)" % (self.Hostname, self.Port)
+        return "Connection data(%s:%d), render(%s:%d)" % \
+            (self.Hostname, self.Port, self.RSHostname, self.RSPort)
+
+    def GetURI(self):
+        """Get URI of the connection"""
+        if not self.Hostname or self.Hostname == "builtin":
+            return "builtin:"
+        if self.Reversed:
+            if not self.RSHostname:
+                return "csrc://%s:%d" % (self.Hostname, self.Port)
+            return "cdsrsrc://%s:%d//%s:%d" % (self.Hostname, self.Port,
+              self.RSHostname, self.RSPort)
+        if not self.RSHostname:
+            return "cs://%s:%d" % (self.Hostname, self.Port)
+        return "cdsrs://%s:%d//%s:%d" % (self.Hostname, self.Port,
+          self.RSHostname, self.RSPort)
+
+    def IsRemote(self):
+        """Returns True if the connection to a remote server, False if
+        it is local (built-in)"""
+        pm = vtkProcessModule.GetProcessModule()
+        if pm.IsRemote(self.ID):
+            return True
+        return False
+
+    def GetNumberOfDataPartitions(self):
+        """Returns the number of partitions on the data server for this
+           connection"""
+        pm = vtkProcessModule.GetProcessModule()
+        return pm.GetNumberOfPartitions(self.ID)
+
+
+## These are methods to create a new connection.
+## One can connect to a server, (data-server,render-server)
+## or simply create a built-in connection.
+## Note: these are internal methods. Use Connect() instead.
+def _connectServer(host, port, rc=False):
+    """Connect to a host:port. Returns the connection object if successfully
+    connected with the server. Internal method, use Connect() instead."""
+    pm =  vtkProcessModule.GetProcessModule()
+    if not rc:
+        cid = pm.ConnectToRemote(host, port)
+        if not cid:
+            return None
+        conn = Connection(cid)
+    else:
+        pm.AcceptConnectionsOnPort(port)
+        print "Waiting for connection..."
+        while True:
+            cid = pm.MonitorConnections(10)
+            if cid > 0:
+                conn = Connection(cid)
+                break
+        pm.StopAcceptingAllConnections()
+    conn.SetHost(host, port, None, None, rc)
+    return conn
+
+def _connectDsRs(ds_host, ds_port, rs_host, rs_port):
+    """Connect to a dataserver at (ds_host:ds_port) and to a render server
+    at (rs_host:rs_port).
+    Returns the connection object if successfully connected
+    with the server. Internal method, use Connect() instead."""
+    pm =  vtkProcessModule.GetProcessModule()
+    cid = pm.ConnectToRemote(ds_host, ds_port, rs_host, rs_port)
+    if not cid:
+        return None
+    conn = Connection(cid)
+    conn.SetHost(ds_host, ds_port, rs_host, rs_port)
+    return conn
+
+def _connectSelf():
+    """Initialises self connection.Internal method, use Connect() instead."""
+    print "Connect to self"
+    pm =  vtkProcessModule.GetProcessModule()
+    pmOptions = pm.GetOptions()
+    if pmOptions.GetProcessType() == 0x40: # PVBATCH
+        return Connection(vtkProcessModuleConnectionManager.GetRootServerConnectionID())
+    cid = pm.ConnectToSelf()
+    if not cid:
+        return None
+    conn = Connection(cid)
+    conn.SetHost("builtin", cid)
+    return conn
+
+def SaveState(filename):
+    """Given a state filename, saves the state of objects registered
+    with the proxy manager."""
+    pm = ProxyManager()
+    pm.SaveState(filename)
+
+def LoadState(filename, connection=None):
+    """Given a state filename and an optional connection, loads the server
+    manager state."""
+    if not connection:
+        connection = ActiveConnection
+    if not connection:
+        raise RuntimeError, "Cannot load state without a connection"
+    loader = vtkSMPQStateLoader()
+    pm = ProxyManager()
+    pm.LoadState(filename, ActiveConnection.ID, loader)
+    views = GetRenderViews()
+    for view in views:
+        # Make sure that the client window size matches the
+        # ViewSize property. In paraview, the GUI takes care
+        # of this.
+        if view.GetClassName() == "vtkSMIceTDesktopRenderViewProxy":
+            view.GetRenderWindow().SetSize(view.ViewSize[0], \
+                                           view.ViewSize[1])
+
+def Connect(ds_host=None, ds_port=11111, rs_host=None, rs_port=11111):
+    """
+    Use this function call to create a new connection. On success,
+    it returns a Connection object that abstracts the connection.
+    Otherwise, it returns None.
+    There are several ways in which this function can be called:
+    * When called with no arguments, it creates a new connection
+      to the built-in server on the client itself.
+    * When called with ds_host and ds_port arguments, it
+      attempts to connect to a server(data and render server on the same server)
+      on the indicated host:port.
+    * When called with ds_host, ds_port, rs_host, rs_port, it
+      creates a new connection to the data server on ds_host:ds_port and to the
+      render server on rs_host: rs_port.
+    """
+    global ActiveConnection
+    global fromGUI
+    if fromGUI:
+        raise RuntimeError, "Cannot create a connection through python. Use the GUI to setup the connection."
+    if ds_host == None:
+        connectionId = _connectSelf()
+    elif rs_host == None:
+        connectionId = _connectServer(ds_host, ds_port)
+    else:
+        connectionId = _connectDsRs(ds_host, ds_port, rs_host, rs_port)
+    if not ActiveConnection:
+        ActiveConnection = connectionId
+    return connectionId
+       
+def ReverseConnect(port=11111):
+    """
+    Use this function call to create a new connection. On success,
+    it returns a Connection object that abstracts the connection.
+    Otherwise, it returns None.
+    In reverse connection mode, the client waits for a connection
+    from the server (client has to be started first). The server
+    then connects to the client (run pvserver with -rc and -ch
+    option).
+    The optional port specified the port to listen to.
+    """
+    global ActiveConnection
+    global fromGUI
+    if fromGUI:
+        raise RuntimeError, "Cannot create a connection through python. Use the GUI to setup the connection."
+    connectionId = _connectServer("Reverse connection", port, True)
+    if not ActiveConnection:
+        ActiveConnection = connectionId
+    return connectionId
+
+def Disconnect(connection=None):
+    """Disconnects the connection. Make sure to clear the proxy manager
+    first."""
+    global ActiveConnection
+    global fromGUI
+    if fromGUI:
+        raise RuntimeError, "Cannot disconnect through python. Use the GUI to disconnect."
+    if not connection or connection == ActiveConnection:
+        connection = ActiveConnection
+        ActiveConnection = None
+    if connection:
+        pm =  vtkProcessModule.GetProcessModule()
+        pm.Disconnect(connection.ID)
+    return
+
+def CreateProxy(xml_group, xml_name, connection=None):
+    """Creates a proxy. If connection is set, the proxy's connection ID is
+    set accordingly. If connection is None, ActiveConnection is used, if
+    present. You should not have to use method normally. Instantiate the
+    appropriate class from the appropriate module, for example:
+    sph = servermanager.sources.SphereSource()"""
+
+    pxm = ProxyManager()
+    aProxy = pxm.NewProxy(xml_group, xml_name)
+    if not aProxy:
+        return None
+    if not connection:
+        connection = ActiveConnection
+    if connection:
+        aProxy.SetConnectionID(connection.ID)
+    return aProxy
+
+def GetRenderView(connection=None):
+    """Return the render view in use.  If more than one render view is in
+    use, return the first one."""
+
+    if not connection:
+        connection = ActiveConnection
+    render_module = None
+    for aProxy in ProxyManager().NewConnectionIterator(connection):
+        if aProxy.IsA("vtkSMRenderViewProxy"):
+            render_module = aProxy
+            break
+    return render_module
+
+def GetRenderViews(connection=None):
+    """Returns the set of all render views."""
+
+    if not connection:
+        connection = ActiveConnection
+    render_modules = []
+    for aProxy in ProxyManager().NewConnectionIterator(connection):
+        if aProxy.IsA("vtkSMRenderViewProxy"):
+            render_modules.append(aProxy)
+    return render_modules
+
+def CreateRenderView(connection=None, **extraArgs):
+    """Creates a render window on the particular connection. If connection
+    is not specified, then the active connection is used, if available.
+
+    This method can also be used to initialize properties by passing
+    keyword arguments where the key is the name of the property.In addition
+    registrationGroup and registrationName (optional) can be specified (as
+    keyword arguments) to automatically register the proxy with the proxy
+    manager."""
+
+    if not connection:
+        connection = ActiveConnection
+    if not connection:
+        raise RuntimeError, "Cannot create render window without connection."
+    pxm = ProxyManager()
+    prototype = pxm.GetPrototypeProxy("views", "RenderView")
+
+    proxy_xml_name = prototype.GetSuggestedViewType(connection.ID)
+    ren_module = None
+    if proxy_xml_name:
+        ren_module = CreateProxy("views", proxy_xml_name, connection)
+    if not ren_module:
+        return None
+    extraArgs['proxy'] = ren_module
+    proxy = rendering.__dict__[ren_module.GetXMLName()](**extraArgs)
+    return proxy
+
+def GetRepresentation(aProxy, view):
+    for rep in view.Representations:
+        #VSV: ==
+        try: isRep = rep.Input.IsSame(aProxy)
+        except: isRep = False
+        if isRep: return rep
+    return None
+
+def CreateRepresentation(aProxy, view, **extraArgs):
+    """Creates a representation for the proxy and adds it to the render
+    module.
+
+    This method can also be used to initialize properties by passing
+    keyword arguments where the key is the name of the property.In addition
+    registrationGroup and registrationName (optional) can be specified (as
+    keyword arguments) to automatically register the proxy with the proxy
+    manager.
+
+    This method tries to create the best possible representation for the given
+    proxy in the given view. Additionally, the user can specify proxyName
+    (optional) to create a representation of a particular type."""
+
+    global rendering
+    if not aProxy:
+        raise RuntimeError, "proxy argument cannot be None."
+    if not view:
+        raise RuntimeError, "render module argument cannot be None."
+    if "proxyName" in extraArgs:
+      display = CreateProxy("representations", extraArgs['proxyName'], None)
+      del extraArgs['proxyName']
+    else:
+      display = view.SMProxy.CreateDefaultRepresentation(aProxy.SMProxy, 0)
+      if display:
+        display.UnRegister(None)
+    if not display:
+        return None
+    display.SetConnectionID(aProxy.GetConnectionID())
+    extraArgs['proxy'] = display
+    proxy = rendering.__dict__[display.GetXMLName()](**extraArgs)
+    proxy.Input = aProxy
+    proxy.UpdateVTKObjects()
+    view.Representations.append(proxy)
+    return proxy
+
+class _ModuleLoader(object):
+    def find_module(self, fullname, path=None):
+        if vtkPVPythonModule.HasModule(fullname):
+            return self
+        else:
+            return None
+    def load_module(self, fullname):
+        import imp
+        moduleInfo = vtkPVPythonModule.GetModule(fullname)
+        if not moduleInfo:
+            raise ImportError
+        module = sys.modules.setdefault(fullname, imp.new_module(fullname))
+        module.__file__ = "<%s>" % moduleInfo.GetFullName()
+        module.__loader__ = self
+        if moduleInfo.GetIsPackage:
+            module.__path__ = moduleInfo.GetFullName()
+        code = compile(moduleInfo.GetSource(), module.__file__, 'exec')
+        exec code in module.__dict__
+        return module
+
+def LoadXML(xmlstring):
+    """Given a server manager XML as a string, parse and process it."""
+    parser = vtkSMXMLParser()
+    if not parser.Parse(xmlstring):
+        raise RuntimeError, "Problem parsing XML string."
+    parser.ProcessConfiguration(vtkSMObject.GetProxyManager())
+    # Update the modules
+    updateModules()
+
+def LoadPlugin(filename,  remote=True, connection=None):
+    """ Given a filename and a connection (optional, otherwise uses
+    ActiveConnection), loads a plugin. It then updates the sources,
+    filters and rendering modules."""
+
+    if not connection:
+        connection = ActiveConnection
+    if not connection:
+        raise RuntimeError, "Cannot load a plugin without a connection."
+
+    pxm=ProxyManager()
+    plm=pxm.GetApplication().GetPluginManager()
+    
+    """ Load the plugin on server. """
+    if remote:
+      serverURI = connection.GetURI()
+    else:
+      serverURI = "builtin:"
+    
+    plinfo = plm.LoadPlugin(filename, connection.ID, serverURI, remote)
+    
+    if not plinfo or not plinfo.GetLoaded():
+        # Assume that it is an xml file
+        f = open(filename, 'r')
+        try:
+            LoadXML(f.read())
+        except RuntimeError:
+            raise RuntimeError, "Problem loading plugin %s: %s" % (filename, pld.GetProperty("Error").GetElement(0))
+    else:
+        updateModules()
+
+
+def Fetch(input, arg1=None, arg2=None, idx=0):
+    """
+    A convenience method that moves data from the server to the client,
+    optionally performing some operation on the data as it moves.
+    The input argument is the name of the (proxy for a) source or filter
+    whose output is needed on the client.
+
+    You can use Fetch to do three things:
+
+    If arg1 is None (the default) then all of the data is brought to the client.
+    In parallel runs an appropriate append Filter merges the
+    data on each processor into one data object. The filter chosen will be
+    vtkAppendPolyData for vtkPolyData, vtkAppendRectilinearGrid for
+    vtkRectilinearGrid, vtkMultiBlockDataGroupFilter for vtkCompositeData,
+    and vtkAppendFilter for anything else.
+
+    If arg1 is an integer then one particular processor's output is brought to
+    the client. In serial runs the arg is ignored. If you have a filter that
+    computes results in parallel and brings them to the root node, then set
+    arg to be 0.
+
+    If arg1 and arg2 are a algorithms, for example vtkMinMax, the algorithm
+    will be applied to the data to obtain some result. Here arg1 will be
+    applied pre-gather and arg2 will be applied post-gather. In parallel
+    runs the algorithm will be run on each processor to make intermediate
+    results and then again on the root processor over all of the
+    intermediate results to create a global result.
+
+    Optional argument idx is used to specify the output port number to fetch the
+    data from. Default is port 0.
+    """
+
+    import types
+
+    #create the pipeline that reduces and transmits the data
+    gvd = rendering.ClientDeliveryRepresentationBase()
+    gvd.AddInput(0, input, idx, "DONTCARE")
+
+    if arg1 == None:
+        print "getting appended"
+
+        cdinfo = input.GetDataInformation(idx).GetCompositeDataInformation()
+        if cdinfo.GetDataIsComposite():
+            print "use composite data append"
+            gvd.SetReductionType(5)
+
+        elif input.GetDataInformation(idx).GetDataClassName() == "vtkPolyData":
+            print "use append poly data filter"
+            gvd.SetReductionType(1)
+
+        elif input.GetDataInformation(idx).GetDataClassName() == "vtkRectilinearGrid":
+            print "use append rectilinear grid filter"
+            gvd.SetReductionType(4)
+
+        elif input.GetDataInformation(idx).IsA("vtkDataSet"):
+            print "use unstructured append filter"
+            gvd.SetReductionType(2)
+
+
+    elif type(arg1) is types.IntType:
+        print "getting node %d" % arg1
+        gvd.SetReductionType(3)
+        gvd.SetPreGatherHelper(None)
+        gvd.SetPostGatherHelper(None)
+        gvd.SetPassThrough(arg1)
+
+    else:
+        print "applying operation"
+        gvd.SetReductionType(6) # CUSTOM
+        gvd.SetPreGatherHelper(arg1)
+        gvd.SetPostGatherHelper(arg2)
+        gvd.SetPassThrough(-1)
+
+    #go!
+    gvd.UpdateVTKObjects()
+    gvd.Update()
+    op = gvd.GetOutput()
+    opc = gvd.GetOutput().NewInstance()
+    opc.ShallowCopy(op)
+    opc.UnRegister(None)
+    return opc
+
+def AnimateReader(reader, view, filename=None):
+    """This is a utility function that, given a reader and a view
+    animates over all time steps of the reader. If the optional
+    filename is provided, a movie is created (type depends on the
+    extension of the filename."""
+    if not reader:
+        raise RuntimeError, "No reader was specified, cannot animate."
+    if not view:
+        raise RuntimeError, "No view was specified, cannot animate."
+    # Create an animation scene
+    scene = animation.AnimationScene()
+
+    # We need to have the reader and the view registered with
+    # the time keeper. This is how the scene gets its time values.
+    try:
+        tk = ProxyManager().GetProxiesInGroup("timekeeper").values()[0]
+        scene.TimeKeeper = tk
+    except IndexError:
+        tk = misc.TimeKeeper()
+        scene.TimeKeeper = tk
+
+    if not reader in tk.TimeSources:
+        tk.TimeSources.append(reader)
+    if not view in tk.Views:
+        tk.Views.append(view)
+
+
+    # with 1 view
+    scene.ViewModules = [view]
+    # Update the reader to get the time information
+    reader.UpdatePipelineInformation()
+    # Animate from 1st time step to last
+    scene.StartTime = reader.TimestepValues.GetData()[0]
+    scene.EndTime = reader.TimestepValues.GetData()[-1]
+
+    # Each frame will correspond to a time step
+    scene.PlayMode = 2 #Snap To Timesteps
+
+    # Create a special animation cue for time.
+    cue = animation.TimeAnimationCue()
+    cue.AnimatedProxy = view
+    cue.AnimatedPropertyName = "ViewTime"
+    scene.Cues = [cue]
+
+    if filename:
+        writer = vtkSMAnimationSceneImageWriter()
+        writer.SetFileName(filename)
+        writer.SetFrameRate(1)
+        writer.SetAnimationScene(scene.SMProxy)
+
+        # Now save the animation.
+        if not writer.Save():
+            raise RuntimeError, "Saving of animation failed!"
+    else:
+        scene.Play()
+    return scene
+
+def ToggleProgressPrinting():
+    """Turn on/off printing of progress (by default, it is on). You can
+    always turn progress off and add your own observer to the process
+    module to handle progress in a custom way. See _printProgress for
+    an example event observer."""
+    pass
+    #vsv global progressObserverTag
+
+    #vsv if fromGUI:
+    #vsv     raise RuntimeError, "Printing progress in the GUI is not supported."
+    #vsv if progressObserverTag:
+    #vsv     vtkProcessModule.GetProcessModule().RemoveObserver(progressObserverTag)
+    #vsv     progressObserverTag = None
+    #VSV Observer is not supported
+    #else:
+    #    progressObserverTag = vtkProcessModule.GetProcessModule().AddObserver("ProgressEvent", _printProgress)
+
+def Finalize():
+   """Although not required, this can be called at exit to cleanup."""
+   global progressObserverTag
+   # Make sure to remove the observer
+   if progressObserverTag:
+       ToggleProgressPrinting()
+   vtkInitializationHelper.Finalize()
+
+# Internal methods
+
+def _getPyProxy(smproxy, outputPort=0):
+    """Returns a python wrapper for a server manager proxy. This method
+    first checks if there is already such an object by looking in the
+    _pyproxies group and returns it if found. Otherwise, it creates a
+    new one. Proxies register themselves in _pyproxies upon creation."""
+    if not smproxy:
+        return None
+    if (smproxy, outputPort) in _pyproxies:
+        return _pyproxies[(smproxy, outputPort)]()
+
+    xmlName = smproxy.GetXMLName()
+    if smproxy.GetXMLLabel():
+        xmlName = smproxy.GetXMLLabel()
+    classForProxy = _findClassForProxy(_make_name_valid(xmlName), smproxy.GetXMLGroup())
+    if classForProxy:
+        retVal = classForProxy(proxy=smproxy, port=outputPort)
+    else:
+        retVal = Proxy(proxy=smproxy, port=outputPort)
+    return retVal
+
+def _makeUpdateCameraMethod(rv):
+    """ This internal method is used to create observer methods """
+    if not hasattr(rv(), "BlockUpdateCamera"):
+        rv().add_attribute("BlockUpdateCamera", False)
+    def UpdateCamera(obj, string):
+        if not rv().BlockUpdateCamera:
+          # used to avoid some nasty recursion that occurs when interacting in
+          # the GUI.
+          rv().BlockUpdateCamera = True
+          rv().SynchronizeCameraProperties()
+          rv().BlockUpdateCamera = False
+    return UpdateCamera
+
+def _createInitialize(group, name):
+    """Internal method to create an Initialize() method for the sub-classes
+    of Proxy"""
+    pgroup = group
+    pname = name
+    def aInitialize(self, connection=None):
+        if not connection:
+            connection = ActiveConnection
+        if not connection:
+            raise RuntimeError,\
+                  'Cannot create a proxy without a connection.'
+        self.InitializeFromProxy(\
+            CreateProxy(pgroup, pname, connection))
+    return aInitialize
+
+def _createGetProperty(pName):
+    """Internal method to create a GetXXX() method where XXX == pName."""
+    propName = pName
+    def getProperty(self):
+        return self.GetPropertyValue(propName)
+    return getProperty
+
+def _createSetProperty(pName):
+    """Internal method to create a SetXXX() method where XXX == pName."""
+    propName = pName
+    def setProperty(self, value):
+        return self.SetPropertyWithName(propName, value)
+    return setProperty
+
+def _findClassForProxy(xmlName, xmlGroup):
+    """Given the xmlName for a proxy, returns a Proxy class. Note
+    that if there are duplicates, the first one is returned."""
+    global sources, filters, rendering, animation, implicit_functions, writers, extended_sources, misc
+    if not xmlName:
+        return None
+    if xmlGroup == "sources":
+        return sources.__dict__[xmlName]
+    elif xmlGroup == "filters":
+        return filters.__dict__[xmlName]
+    elif xmlGroup == "implicit_functions":
+        return implicit_functions.__dict__[xmlName]
+    elif xmlGroup == "writers":
+        return writers.__dict__[xmlName]
+    elif xmlGroup == "extended_sources":
+        return extended_sources.__dict__[xmlName]
+    elif xmlName in rendering.__dict__:
+        return rendering.__dict__[xmlName]
+    elif xmlName in animation.__dict__:
+        return animation.__dict__[xmlName]
+    elif xmlName in misc.__dict__:
+        return misc.__dict__[xmlName]
+    else:
+        return None
+
+def _printProgress(caller, event):
+    """The default event handler for progress. Prints algorithm
+    name and 1 '.' per 10% progress."""
+    global currentAlgorithm, currentProgress
+
+    pm = vtkProcessModule.GetProcessModule()
+    progress = pm.GetLastProgress() / 10
+    # If we got a 100% as the first thing, ignore
+    # This is to get around the fact that some vtk
+    # algorithms report 100% more than once (which is
+    # a bug)
+    if not currentAlgorithm and progress == 10:
+        return
+    alg = pm.GetLastProgressName()
+    if alg != currentAlgorithm and alg:
+        if currentAlgorithm:
+            while currentProgress <= 10:
+                import sys
+                sys.stdout.write(".")
+                currentProgress += 1
+            print "]"
+            currentProgress = 0
+        print alg, ": [ ",
+        currentAlgorithm = alg
+    while currentProgress <= progress:
+        import sys
+        sys.stdout.write(".")
+        #sys.stdout.write("%d " % pm.GetLastProgress())
+        currentProgress += 1
+    if progress == 10:
+        print "]"
+        currentAlgorithm = None
+        currentProgress = 0
+
+def updateModules():
+    """Called when a plugin is loaded, this method updates
+    the proxy class object in all known modules."""
+    global sources, filters, writers, rendering, animation, implicit_functions, extended_sources, misc
+
+    createModule("sources", sources)
+    createModule("filters", filters)
+    createModule("writers", writers)
+    createModule("representations", rendering)
+    createModule("views", rendering)
+    createModule("lookup_tables", rendering)
+    createModule("textures", rendering)
+    createModule("animation", animation)
+    createModule("misc", misc)
+    createModule('animation_keyframes', animation)
+    createModule('implicit_functions', implicit_functions)
+    createModule("extended_sources", extended_sources)
+
+def _createModules():
+    """Called when the module is loaded, this creates sub-
+    modules for all know proxy groups."""
+    global sources, filters, writers, rendering, animation, implicit_functions, extended_sources, misc
+
+    sources = createModule('sources')
+    filters = createModule('filters')
+    writers = createModule('writers')
+    rendering = createModule('representations')
+    createModule('views', rendering)
+    createModule("lookup_tables", rendering)
+    createModule("textures", rendering)
+    animation = createModule('animation')
+    createModule('animation_keyframes', animation)
+    implicit_functions = createModule('implicit_functions')
+    extended_sources = createModule("extended_sources")
+    misc = createModule("misc")
+
+class PVModule(object):
+    pass
+
+def _make_name_valid(name):
+    "Make a string into a valid Python variable name"
+    if not name:
+        return None
+    if name.find('(') >= 0 or name.find(')') >=0:
+        return None
+    name = name.replace(' ','')
+    name = name.replace('-','')
+    name = name.replace(':','')
+    name = name.replace('.','')
+    if not name[0].isalpha():
+        name = 'a' + name
+    return name
+
+def createModule(groupName, mdl=None):
+    """Populates a module with proxy classes defined in the given group.
+    If mdl is not specified, it also creates the module"""
+
+    pxm = vtkSMObject.GetProxyManager()
+    # Use prototypes to find all proxy types.
+    pxm.InstantiateGroupPrototypes(groupName)
+
+    debug = False
+    if not mdl:
+        debug = True
+        mdl = PVModule()
+    numProxies = pxm.GetNumberOfXMLProxies(groupName)
+    for i in range(numProxies):
+        proxyName = pxm.GetXMLProxyName(groupName, i)
+        proto = pxm.GetPrototypeProxy(groupName, proxyName)
+        if proto.GetXMLLabel():
+            pname = proto.GetXMLLabel()
+        pname = _make_name_valid(pname)
+        if not pname:
+            continue
+        if pname in mdl.__dict__:
+            if debug:
+                print "Warning: %s is being overwritten. This may point to an issue in the ParaView configuration files" % pname
+        cdict = {}
+        # Create an Initialize() method for this sub-class.
+        cdict['Initialize'] = _createInitialize(groupName, proxyName)
+        iter = PropertyIterator(proto)
+        # Add all properties as python properties.
+        for prop in iter:
+            propName = iter.GetKey()
+            if (prop.GetInformationOnly() and propName != "TimestepValues" ) or prop.GetIsInternal():
+                continue
+            names = [propName]
+            names = [iter.PropertyLabel]
+                
+            propDoc = None
+            if prop.GetDocumentation():
+                propDoc = prop.GetDocumentation().GetDescription()
+            for name in names:
+                name = _make_name_valid(name)
+                if name:
+                    cdict[name] = property(_createGetProperty(propName),
+                                           _createSetProperty(propName),
+                                           None,
+                                           propDoc)
+        # Add the documentation as the class __doc__
+        if proto.GetDocumentation() and proto.GetDocumentation().GetDescription():
+            doc = proto.GetDocumentation().GetDescription()
+        #else:
+        doc = Proxy.__doc__
+        cdict['__doc__'] = doc
+        # Create the new type
+        if proto.GetXMLName() == "ExodusIIReader":
+            superclasses = (ExodusIIReaderProxy,)
+        elif proto.IsA("vtkSMSourceProxy"):
+            superclasses = (SourceProxy,)
+        else:
+            superclasses = (Proxy,)
+
+        cobj = type(pname, superclasses, cdict)
+        # Add it to the modules dictionary
+        mdl.__dict__[pname] = cobj
+    return mdl
+
+
+def __determineGroup(proxy):
+    """Internal method"""
+    if not proxy:
+        return None
+    xmlgroup = proxy.GetXMLGroup()
+    xmlname = proxy.GetXMLName()
+    if xmlgroup == "sources":
+        return "sources"
+    elif xmlgroup == "filters":
+        return "sources"
+    elif xmlgroup == "views":
+        return "views"
+    elif xmlgroup == "representations":
+        if xmlname == "ScalarBarWidgetRepresentation":
+            return "scalar_bars"
+        return "representations"
+    elif xmlgroup == "lookup_tables":
+        return "lookup_tables"
+    elif xmlgroup == "implicit_functions":
+        return "implicit_functions"
+    return None
+
+__nameCounter = {}
+def __determineName(proxy, group):
+    global __nameCounter
+    name = _make_name_valid(proxy.GetXMLLabel())
+    if not name:
+        return None
+    if not __nameCounter.has_key(name):
+        __nameCounter[name] = 1
+        val = 1
+    else:
+        __nameCounter[name] += 1
+        val = __nameCounter[name]
+    return "%s%d" % (name, val)
+
+def __getName(proxy, group):
+    pxm = ProxyManager()
+    if isinstance(proxy, Proxy):
+        proxy = proxy.SMProxy
+    return pxm.GetProxyName(group, proxy)
+
+class MissingRegistrationInformation(Exception):
+    """Exception for missing registration information. Raised when a name or group 
+    is not specified or when a group cannot be deduced."""
+    pass
+    
+def Register(proxy, **extraArgs):
+    """Registers a proxy with the proxy manager. If no 'registrationGroup' is
+    specified, then the group is inferred from the type of the proxy.
+    'registrationName' may be specified to register with a particular name
+    otherwise a default name will be created."""
+    # TODO: handle duplicate registration
+    if "registrationGroup" in extraArgs:
+        registrationGroup = extraArgs["registrationGroup"]
+    else:
+        registrationGroup = __determineGroup(proxy)
+
+    if "registrationName" in extraArgs:
+        registrationName = extraArgs["registrationName"]
+    else:
+        registrationName = __determineName(proxy, registrationGroup)
+    if registrationGroup and registrationName:
+        pxm = ProxyManager()
+        pxm.RegisterProxy(registrationGroup, registrationName, proxy)
+    else:
+        raise MissingRegistrationInformation, "Registration error %s %s." % (registrationGroup, registrationName)
+    return (registrationGroup, registrationName)
+
+def UnRegister(proxy, **extraArgs):
+    """UnRegisters proxies registered using Register()."""
+    if "registrationGroup" in extraArgs:
+        registrationGroup = extraArgs["registrationGroup"]
+    else:
+        registrationGroup = __determineGroup(proxy)
+
+    if "registrationName" in extraArgs:
+        registrationName = extraArgs["registrationName"]
+    else:
+        registrationName = __getName(proxy, registrationGroup)
+
+    if registrationGroup and registrationName:
+        pxm = ProxyManager()
+        pxm.UnRegisterProxy(registrationGroup, registrationName, proxy)
+    else:
+        raise RuntimeError, "UnRegistration error."
+    return (registrationGroup, registrationName)
+
+def demo1():
+    """This simple demonstration creates a sphere, renders it and delivers
+    it to the client using Fetch. It returns a tuple of (data, render
+    view)"""
+    if not ActiveConnection:
+        Connect()
+    ss = sources.Sphere(Radius=2, ThetaResolution=32)
+    shr = filters.Shrink(Input=OutputPort(ss,0))
+    cs = sources.Cone()
+    app = filters.AppendDatasets()
+    app.Input = [shr, cs]
+    rv = CreateRenderView()
+    rep = CreateRepresentation(app, rv)
+    rv.ResetCamera()
+    rv.StillRender()
+    data = Fetch(ss)
+
+    return (data, rv)
+
+def demo2(fname="/Users/berk/Work/ParaViewData/Data/disk_out_ref.ex2"):
+    """This method demonstrates the user of a reader, representation and
+    view. It also demonstrates how meta-data can be obtained using proxies.
+    Make sure to pass the full path to an exodus file. Also note that certain
+    parameters are hard-coded for disk_out_ref.ex2 which can be found
+    in ParaViewData. This method returns the render view."""
+    if not ActiveConnection:
+        Connect()
+    # Create the exodus reader and specify a file name
+    reader = sources.ExodusIIReader(FileName=fname)
+    # Get the list of point arrays.
+    arraySelection = reader.PointVariables
+    print arraySelection.Available
+    # Select all arrays
+    arraySelection.SetData(arraySelection.Available)
+
+    # Next create a default render view appropriate for the connection type.
+    rv = CreateRenderView()
+    # Create the matching representation
+    rep = CreateRepresentation(reader, rv)
+    rep.Representation = 1 # Wireframe
+    # Black background is not pretty
+    rv.Background = [0.4, 0.4, 0.6]
+    rv.StillRender()
+    # Reset the camera to include the whole thing
+    rv.ResetCamera()
+    rv.StillRender()
+    # Change the elevation of the camera. See VTK documentation of vtkCamera
+    # for camera parameters.
+    c = rv.GetActiveCamera()
+    c.Elevation(45)
+    rv.StillRender()
+    # Now that the reader execute, let's get some information about it's
+    # output.
+    pdi = reader[0].PointData
+    # This prints a list of all read point data arrays as well as their
+    # value ranges.
+    print 'Number of point arrays:', len(pdi)
+    for i in range(len(pdi)):
+        ai = pdi[i]
+        print "----------------"
+        print "Array:", i, ai.Name, ":"
+        numComps = ai.GetNumberOfComponents()
+        print "Number of components:", numComps
+        for j in range(numComps):
+            print "Range:", ai.GetRange(j)
+    # White is boring. Let's color the geometry using a variable.
+    # First create a lookup table. This object controls how scalar
+    # values are mapped to colors. See VTK documentation for
+    # details.
+    lt = rendering.PVLookupTable()
+    # Assign it to the representation
+    rep.LookupTable = lt
+    # Color by point array called Pres
+    rep.ColorAttributeType = 0 # point data
+    rep.ColorArrayName = "Pres"
+    # Add to RGB points. These are tuples of 4 values. First one is
+    # the scalar values, the other 3 the RGB values. This list has
+    # 2 points: Pres: 0.00678, color: blue, Pres: 0.0288, color: red
+    lt.RGBPoints = [0.00678, 0, 0, 1, 0.0288, 1, 0, 0]
+    lt.ColorSpace = 1 # HSV
+    rv.StillRender()
+    return rv
+
+def demo3():
+    """This method demonstrates the use of servermanager with numpy as
+    well as pylab for plotting. It creates an artificial data sources,
+    probes it with a line, delivers the result to the client using Fetch
+    and plots it using pylab. This demo requires numpy and pylab installed.
+    It returns a tuple of (data, render view)."""
+    import paraview.numpy_support
+    import pylab
+
+    if not ActiveConnection:
+        Connect()
+    # Create a synthetic data source
+    source = sources.Wavelet()
+    # Let's get some information about the data. First, for the
+    # source to execute
+    source.UpdatePipeline()
+
+    di = source.GetDataInformation()
+    print "Data type:", di.GetPrettyDataTypeString()
+    print "Extent:", di.GetExtent()
+    print "Array name:", \
+          source[0].PointData[0].Name
+
+    rv = CreateRenderView()
+
+    rep1 = CreateRepresentation(source, rv)
+    rep1.Representation = 3 # outline
+
+    # Let's apply a contour filter
+    cf = filters.Contour(Input=source, ContourValues=[200])
+
+    # Select the array to contour by
+    #cf.SelectInputScalars = 'RTData'
+
+    rep2 = CreateRepresentation(cf, rv)
+
+    rv.Background = (0.4, 0.4, 0.6)
+    # Reset the camera to include the whole thing
+    rv.StillRender()
+    rv.ResetCamera()
+    rv.StillRender()
+
+    # Now, let's probe the data
+    probe = filters.ResampleWithDataset(Input=source)
+    # with a line
+    line = sources.Line(Resolution=60)
+    # that spans the dataset
+    bounds = di.GetBounds()
+    print "Bounds: ", bounds
+    line.Point1 = bounds[0:6:2]
+    line.Point2 = bounds[1:6:2]
+
+    probe.Source = line
+
+    # Render with the line
+    rep3 = CreateRepresentation(line, rv)
+    rv.StillRender()
+
+    # Now deliver it to the client. Remember, this is for small data.
+    data = Fetch(probe)
+    # Convert it to a numpy array
+    data = paraview.numpy_support.vtk_to_numpy(
+      data.GetPointData().GetArray("RTData"))
+    # Plot it using matplotlib
+    pylab.plot(data)
+    pylab.show()
+
+    return (data, rv, probe)
+
+def demo4(fname="/Users/berk/Work/ParaViewData/Data/can.ex2"):
+    """This method demonstrates the user of AnimateReader for
+    creating animations."""
+    if not ActiveConnection:
+        Connect()
+    reader = sources.ExodusIIReader(FileName=fname)
+    view = CreateRenderView()
+    repr = CreateRepresentation(reader, view)
+    view.StillRender()
+    view.ResetCamera()
+    view.StillRender()
+    c = view.GetActiveCamera()
+    c.Elevation(95)
+    return AnimateReader(reader, view)
+
+
+def demo5():
+    """ Simple sphere animation"""
+    if not ActiveConnection:
+        Connect()
+    sphere = sources.Sphere()
+    view = CreateRenderView()
+    repr = CreateRepresentation(sphere, view)
+
+    view.StillRender()
+    view.ResetCamera()
+    view.StillRender()
+
+    # Create an animation scene
+    scene = animation.AnimationScene()
+    # Add 1 view
+    scene.ViewModules = [view]
+
+    # Create a cue to animate the StartTheta property
+    cue = animation.KeyFrameAnimationCue()
+    cue.AnimatedProxy = sphere
+    cue.AnimatedPropertyName = "StartTheta"
+    # Add it to the scene's cues
+    scene.Cues = [cue]
+
+    # Create 2 keyframes for the StartTheta track
+    keyf0 = animation.CompositeKeyFrame()
+    keyf0.Type = 2 # Set keyframe interpolation type to Ramp.
+    # At time = 0, value = 0
+    keyf0.KeyTime = 0
+    keyf0.KeyValues= [0]
+
+    keyf1 = animation.CompositeKeyFrame()
+    # At time = 1.0, value = 200
+    keyf1.KeyTime = 1.0
+    keyf1.KeyValues= [200]
+
+    # Add keyframes.
+    cue.KeyFrames = [keyf0, keyf1]
+
+    scene.Play()
+    return scene
+
+ASSOCIATIONS = { 'POINTS' : 0, 'CELLS' : 1, 'VERTICES' : 4, 'EDGES' : 5, 'ROWS' : 6}
+
+# Users can set the active connection which will be used by API
+# to create proxies etc when no connection argument is passed.
+# Connect() automatically sets this if it is not already set.
+ActiveConnection = None
+
+# Needs to be called when paraview module is loaded from python instead
+# of pvpython, pvbatch or GUI.
+if not vtkSMObject.GetProxyManager():
+    vtkInitializationHelper.Initialize(sys.executable)
+
+# Initialize progress printing. Can be turned off by calling
+# ToggleProgressPrinting() again.
+progressObserverTag = None
+currentAlgorithm = False
+currentProgress = 0
+fromGUI = False
+ToggleProgressPrinting()
+
+_pyproxies = {}
+
+# Create needed sub-modules
+_createModules()
+
+# Set up our custom importer (if possible)
+loader = _ModuleLoader()
+sys.meta_path.append(loader)
+
+# Definitions for working in SALOME GUI mode
+aParams = myParavis.GetConnectionParameters()
+ActiveConnection = Connection(aParams[0])
+ActiveConnection.SetHost(aParams[1], aParams[2], aParams[3], aParams[4], aParams[5])
+ToggleProgressPrinting()
+fromGUI = True
+
+print vtkSMProxyManager.GetParaViewSourceVersion();
+
diff --git a/src/PV_SWIG/pvsimple.py b/src/PV_SWIG/pvsimple.py
new file mode 100644 (file)
index 0000000..54d6aa9
--- /dev/null
@@ -0,0 +1,681 @@
+r"""simple is a module for using paraview server manager in Python. It 
+provides a simple convenience layer to functionality provided by the
+C++ classes wrapped to Python as well as the servermanager module.
+
+A simple example:
+  from paraview.simple import *
+
+  # Create a new sphere proxy on the active connection and register it
+  # in the sources group.
+  sphere = Sphere(ThetaResolution=16, PhiResolution=32)
+
+  # Apply a shrink filter
+  shrink = Shrink(sphere)
+  
+  # Turn the visiblity of the shrink object on.
+  Show(shrink)
+  
+  # Render the scene
+  Render()
+"""
+
+import paravisSM
+
+servermanager = paravisSM
+
+def Connect(ds_host=None, ds_port=11111, rs_host=None, rs_port=11111):
+    """Creates a connection to a server. Example usage:
+    > Connect("amber") # Connect to a single server at default port
+    > Connect("amber", 12345) # Connect to a single server at port 12345
+    > Connect("amber", 11111, "vis_cluster", 11111) # connect to data server, render server pair
+    This also create a default render view."""
+    servermanager.ProxyManager().UnRegisterProxies()
+    active_objects.view = None
+    active_objects.source = None
+    import gc
+    gc.collect()
+    servermanager.Disconnect()
+    cid = servermanager.Connect(ds_host, ds_port, rs_host, rs_port)
+    servermanager.ProxyManager().RegisterProxy("timekeeper", "tk", servermanager.misc.TimeKeeper())
+
+    return cid
+
+def CreateRenderView():
+    "Creates and returns a 3D render view."
+    view = servermanager.CreateRenderView()
+    servermanager.ProxyManager().RegisterProxy("views", \
+      "my_view%d" % _funcs_internals.view_counter, view)
+    active_objects.view = view
+    _funcs_internals.view_counter += 1
+    
+    tk = servermanager.ProxyManager().GetProxiesInGroup("timekeeper").values()[0]
+    views = tk.Views
+    if not view in views:
+        views.append(view)
+
+    return view
+
+def GetRenderView():
+    "Returns the active view if there is one. Else creates and returns a new view."
+    view = active_objects.view
+    if not view: view = CreateRenderView()
+    return view
+
+def GetRenderViews():
+    "Returns all render views as a list."
+    return servermanager.GetRenderViews()
+
+def GetRepresentation(proxy=None, view=None):
+    """"Given a pipeline object and view, returns the corresponding representation object.
+    If pipeline object and view are not specified, active objects are used."""
+    if not view:
+        view = active_objects.view
+    if not proxy:
+        proxy = active_objects.source
+    rep = servermanager.GetRepresentation(proxy, view)
+    if not rep:
+        rep = servermanager.CreateRepresentation(proxy, view)
+        servermanager.ProxyManager().RegisterProxy("representations", \
+          "my_representation%d" % _funcs_internals.rep_counter, rep)
+        _funcs_internals.rep_counter += 1
+    return rep
+    
+def GetDisplayProperties(proxy=None, view=None):
+    """"Given a pipeline object and view, returns the corresponding representation object.
+    If pipeline object and/or view are not specified, active objects are used."""
+    return GetRepresentation(proxy, view)
+    
+def Show(proxy=None, view=None, **params):
+    """Turns the visibility of a given pipeline object on in the given view.
+    If pipeline object and/or view are not specified, active objects are used."""
+    if proxy == None:
+        proxy = GetActiveSource()
+    if proxy == None:
+        raise RuntimeError, "Show() needs a proxy argument or that an active source is set."
+    if not view and len(GetRenderViews()) == 0:
+        CreateRenderView()
+    rep = GetDisplayProperties(proxy, view)
+    if rep == None:
+        raise RuntimeError, "Could not create a representation object for proxy %s" % proxy.GetXMLLabel()
+    for param in params.keys():
+        setattr(rep, param, params[param])
+    rep.Visibility = 1
+    return rep
+
+def Hide(proxy=None, view=None):
+    """Turns the visibility of a given pipeline object off in the given view.
+    If pipeline object and/or view are not specified, active objects are used."""
+    rep = GetDisplayProperties(proxy, view)
+    rep.Visibility = 0
+
+def Render(view=None):
+    """Renders the given view (default value is active view)"""
+    if not view:
+        view = active_objects.view
+    view.StillRender()
+    if _funcs_internals.first_render:
+        view.ResetCamera()
+        view.StillRender()
+        _funcs_internals.first_render = False
+    return view
+        
+def ResetCamera(view=None):
+    """Resets the settings of the camera to preserver orientation but include
+    the whole scene. If an argument is not provided, the active view is
+    used."""
+    if not view:
+        view = active_objects.view
+    view.ResetCamera()
+    Render(view)
+
+def SetProperties(proxy=None, **params):
+    """Sets one or more properties of the given pipeline object. If an argument
+    is not provided, the active source is used. Pass a list of property_name=value
+    pairs to this function to set property values. For example:
+     SetProperties(Center=[1, 2, 3], Radius=3.5)
+    """
+    if not proxy:
+        proxy = active_objects.source
+    for param in params.keys():
+        if not hasattr(proxy, param):
+            raise AttributeError("object has no property %s" % param)
+        setattr(proxy, param, params[param])
+
+def SetDisplayProperties(proxy=None, view=None, **params):
+    """Sets one or more display properties of the given pipeline object. If an argument
+    is not provided, the active source is used. Pass a list of property_name=value
+    pairs to this function to set property values. For example:
+     SetProperties(Color=[1, 0, 0], LineWidth=2)
+    """
+    rep = GetDisplayProperties(proxy, view)
+    SetProperties(rep, **params)
+
+def SetViewProperties(view=None, **params):
+    """Sets one or more properties of the given view. If an argument
+    is not provided, the active view is used. Pass a list of property_name=value
+    pairs to this function to set property values. For example:
+     SetProperties(Background=[1, 0, 0], UseImmediateMode=0)
+    """
+    if not view:
+        view = active_objects.view
+    SetProperties(view, **params)
+
+def RenameSource(newName, proxy=None):
+    """Renames the given source.  If the given proxy is not registered
+    in the sources group this method will have no effect.  If no source is
+    provided, the active source is used."""
+    if not proxy:
+        proxy = active_objects.source
+    pxm = servermanager.ProxyManager()
+    oldName = pxm.GetProxyName("sources", proxy)
+    if oldName:
+      pxm.RegisterProxy("sources", newName, proxy)
+      pxm.UnRegisterProxy("sources", oldName, proxy)
+
+def FindSource(name):
+    return servermanager.ProxyManager().GetProxy("sources", name)
+
+def GetSources():
+    """Given the name of a source, return its Python object."""
+    return servermanager.ProxyManager().GetProxiesInGroup("sources")
+
+def GetRepresentations():
+    """Returns all representations (display properties)."""
+    return servermanager.ProxyManager().GetProxiesInGroup("representations")
+
+def UpdatePipeline(time=None, proxy=None):
+    """Updates (executes) the given pipeline object for the given time as
+    necessary (i.e. if it did not already execute). If no source is provided,
+    the active source is used instead."""
+    if not proxy:
+        proxy = active_objects.source
+    if time:
+        proxy.UpdatePipeline(time)
+    else:
+        proxy.UpdatePipeline()
+
+def Delete(proxy=None):
+    """Deletes the given pipeline object or the active source if no argument
+    is specified."""
+    if not proxy:
+        proxy = active_objects.source
+    # Unregister any helper proxies stored by a vtkSMProxyListDomain
+    for prop in proxy:
+        listdomain = prop.GetDomain('proxy_list')
+        if listdomain:
+            if listdomain.GetClassName() != 'vtkSMProxyListDomain':
+                continue
+            group = "pq_helper_proxies." + proxy.GetSelfIDAsString()
+            for i in xrange(listdomain.GetNumberOfProxies()):
+                pm = servermanager.ProxyManager()
+                iproxy = listdomain.GetProxy(i)
+                name = pm.GetProxyName(group, iproxy)
+                if iproxy and name:
+                    pm.UnRegisterProxy(group, name, iproxy)
+                    
+    # Remove source/view from time keeper
+    tk = servermanager.ProxyManager().GetProxiesInGroup("timekeeper").values()[0]
+    if isinstance(proxy, servermanager.SourceProxy):
+        try:
+            idx = tk.TimeSources.index(proxy)
+            del tk.TimeSources[idx]
+        except ValueError:
+            pass
+    else:
+        try:
+            idx = tk.Views.index(proxy)
+            del tk.Views[idx]
+        except ValueError:
+            pass
+    servermanager.UnRegister(proxy)
+    
+    # If this is a representation, remove it from all views.
+    if proxy.SMProxy.IsA("vtkSMRepresentationProxy"):
+        for view in GetRenderViews():
+            view.Representations.remove(proxy)
+    # If this is a source, remove the representation iff it has no consumers
+    # Also change the active source if necessary
+    elif proxy.SMProxy.IsA("vtkSMSourceProxy"):
+        sources = servermanager.ProxyManager().GetProxiesInGroup("sources")
+        for i in range(proxy.GetNumberOfConsumers()):
+            if proxy.GetConsumerProxy(i) in sources:
+                raise RuntimeError("Source has consumers. It cannot be deleted " +
+                  "until all consumers are deleted.")
+        #VSV:==
+        if proxy.IsSame(GetActiveSource()):
+            if hasattr(proxy, "Input") and proxy.Input:
+                if isinstance(proxy.Input, servermanager.Proxy):
+                    SetActiveSource(proxy.Input)
+                else:
+                    SetActiveSource(proxy.Input[0])
+            else: SetActiveSource(None)
+        for rep in GetRepresentations().values():
+            #VSV:==
+            if rep.Input.IsSame(proxy):
+                Delete(rep)
+    # Change the active view if necessary
+    elif proxy.SMProxy.IsA("vtkSMRenderViewProxy"):
+        ##VSV:==
+        if proxy.IsSame(GetActiveView()):
+            if len(GetRenderViews()) > 0:
+                SetActiveView(GetRenderViews()[0])
+            else:
+                SetActiveView(None)
+
+def CreateLookupTable(**params):
+    """Create and return a lookup table.  Optionally, parameters can be given
+    to assign to the lookup table.
+    """
+    lt = servermanager.rendering.PVLookupTable()
+    servermanager.Register(lt)
+    SetProperties(lt, **params)
+    return lt
+
+def CreateScalarBar(**params):
+    """Create and return a scalar bar widget.  The returned widget may
+    be added to a render view by appending it to the view's representations
+    The widget must have a valid lookup table before it is added to a view.
+    It is possible to pass the lookup table (and other properties) as arguments
+    to this method:
+    
+    lt = MakeBlueToRedLt(3.5, 7.5)
+    bar = CreateScalarBar(LookupTable=lt, Title="Velocity")
+    GetRenderView().Representations.append(bar)
+    
+    By default the returned widget is selectable and resizable.
+    """
+    sb = servermanager.rendering.ScalarBarWidgetRepresentation()
+    servermanager.Register(sb)
+    sb.Selectable = 1
+    sb.Resizable = 1
+    sb.Enabled = 1
+    sb.Title = "Scalars"
+    SetProperties(sb, **params)
+    return sb
+
+# TODO: Change this to take the array name and number of components. Register 
+# the lt under the name ncomp.array_name
+def MakeBlueToRedLT(min, max):
+    # Define RGB points. These are tuples of 4 values. First one is
+    # the scalar values, the other 3 the RGB values. 
+    rgbPoints = [min, 0, 0, 1, max, 1, 0, 0]
+    return CreateLookupTable(RGBPoints=rgbPoints, ColorSpace="HSV")
+    
+def _find_writer(filename):
+    "Internal function."
+    extension = None
+    parts = filename.split('.')
+    if len(parts) > 1:
+        extension = parts[-1]
+    else:
+        raise RuntimeError, "Filename has no extension, please specify a write"
+        
+    if extension == 'png':
+        return 'vtkPNGWriter'
+    elif extension == 'bmp':
+        return 'vtkBMPWriter'
+    elif extension == 'ppm':
+        return vtkPNMWriter
+    elif extension == 'tif' or extension == 'tiff':
+        return 'vtkTIFFWriter'
+    elif extension == 'jpg' or extension == 'jpeg':
+        return 'vtkJPEGWriter'
+    else:
+        raise RuntimeError, "Cannot infer filetype from extension:", extension
+
+def AddCameraLink(viewProxy, viewProxyOther, linkName):
+    """Create a camera link between two view proxies.  A name must be given
+    so that the link can be referred to by name.  If a link with the given
+    name already exists it will be removed first."""
+    if not viewProxyOther: viewProxyOther = GetActiveView()
+    link = servermanager.vtkSMCameraLink()
+    link.AddLinkedProxy(viewProxy.SMProxy, 1)
+    link.AddLinkedProxy(viewProxyOther.SMProxy, 2)
+    link.AddLinkedProxy(viewProxyOther.SMProxy, 1)
+    link.AddLinkedProxy(viewProxy.SMProxy, 2)
+    RemoveCameraLink(linkName)
+    servermanager.ProxyManager().RegisterLink(linkName, link)
+
+def RemoveCameraLink(linkName):
+    """Remove a camera link with the given name."""
+    servermanager.ProxyManager().UnRegisterLink(linkName)
+
+def WriteImage(filename, view=None, **params):
+    """Saves the given view (or the active one if none is given) as an
+    image. Optionally, you can specify the writer and the magnification
+    using the Writer and Magnification named arguments. For example:
+     WriteImage("foo.mypng", aview, Writer=vtkPNGWriter, Magnification=2)
+    If no writer is provided, the type is determined from the file extension.
+    Currently supported extensions are png, bmp, ppm, tif, tiff, jpg and jpeg.
+    The writer is a VTK class that is capable of writing images.
+    Magnification is used to determine the size of the written image. The size
+    is obtained by multiplying the size of the view with the magnification.
+    Rendering may be done using tiling to obtain the correct size without
+    resizing the view."""
+    if not view:
+        view = active_objects.view
+    writer = None
+    if params.has_key('Writer'):
+        writer = params['Writer']
+    mag = 1
+    if params.has_key('Magnification'):
+        mag = int(params['Magnification'])
+    if not writer:
+        writer = _find_writer(filename)
+    view.WriteImage(filename, writer, mag)
+
+def AnimateReader(reader=None, view=None, filename=None):
+    """This is a utility function that, given a reader and a view
+    animates over all time steps of the reader. If the optional
+    filename is provided, a movie is created (type depends on the
+    extension of the filename."""
+    if not reader:
+        reader = active_objects.source
+    if not view:
+        view = active_objects.view
+        
+    return servermanager.AnimateReader(reader, view, filename)
+
+
+def _create_func(key, module):
+    "Internal function."
+
+    def CreateObject(*input, **params):
+        """This function creates a new proxy. For pipeline objects that accept inputs,
+        all non-keyword arguments are assumed to be inputs. All keyword arguments are
+        assumed to be property,value pairs and are passed to the new proxy."""
+
+        # Instantiate the actual object from the given module.
+        px = module.__dict__[key]()
+
+        # Make sure non-keyword arguments are valid
+        for inp in input:
+            if inp != None and not isinstance(inp, servermanager.Proxy):
+                if px.GetProperty("Input") != None:
+                    raise RuntimeError, "Expecting a proxy as input."
+                else:
+                    raise RuntimeError, "This function does not accept non-keyword arguments."
+
+        # Assign inputs
+        if px.GetProperty("Input") != None:
+            if len(input) > 0:
+                px.Input = input
+            else:
+                # If no input is specified, try the active pipeline object
+                if px.GetProperty("Input").GetRepeatable() and active_objects.get_selected_sources():
+                    px.Input = active_objects.get_selected_sources()
+                elif active_objects.source:
+                    px.Input = active_objects.source
+        else:
+            if len(input) > 0:
+                raise RuntimeError, "This function does not expect an input."
+
+        registrationName = None
+        for nameParam in ['registrationName', 'guiName']:
+          if nameParam in params:
+              registrationName = params[nameParam]
+              del params[nameParam]
+
+        # Pass all the named arguments as property,value pairs
+        for param in params.keys():
+            setattr(px, param, params[param])
+
+        try:
+            # Register the proxy with the proxy manager.
+            if registrationName:
+                group, name = servermanager.Register(px, registrationName=registrationName)
+            else:
+                group, name = servermanager.Register(px)
+
+
+            # Register pipeline objects with the time keeper. This is used to extract time values
+            # from sources. NOTE: This should really be in the servermanager controller layer.
+            if group == "sources":
+                tk = servermanager.ProxyManager().GetProxiesInGroup("timekeeper").values()[0]
+                sources = tk.TimeSources
+                if not px in sources:
+                    sources.append(px)
+
+                active_objects.source = px
+        except servermanager.MissingRegistrationInformation:
+            pass
+
+        return px
+
+    return CreateObject
+
+def _create_doc(new, old):
+    "Internal function."
+    import string
+    res = ""
+    for doc in (new, old):
+        ts = []
+        strpd = doc.split('\n')
+        for s in strpd:
+            ts.append(s.lstrip())
+        res += string.join(ts)
+        res += '\n'
+    return res
+    
+def _func_name_valid(name):
+    "Internal function."
+    valid = True
+    for c in name:
+        if c == '(' or c ==')':
+            valid = False
+            break
+    return valid
+
+def _add_functions(g):
+    for m in [servermanager.filters, servermanager.sources, servermanager.writers]:
+        dt = m.__dict__
+        for key in dt.keys():
+            cl = dt[key]
+            if not isinstance(cl, str):
+                if not key in g and _func_name_valid(key):
+                    g[key] = _create_func(key, m)
+                    exec "g[key].__doc__ = _create_doc(m.%s.__doc__, g[key].__doc__)" % key
+
+def GetActiveView():
+    "Returns the active view."
+    return active_objects.view
+    
+def SetActiveView(view):
+    "Sets the active view."
+    active_objects.view = view
+    
+def GetActiveSource():
+    "Returns the active source."
+    return active_objects.source
+    
+def SetActiveSource(source):
+    "Sets the active source."
+    active_objects.source = source
+    
+def GetActiveCamera():
+    """Returns the active camera for the active view. The returned object
+    is an instance of vtkCamera."""
+    return GetActiveView().GetActiveCamera()
+
+def LoadXML(xmlstring, ns=None):
+    """Given a server manager XML as a string, parse and process it.
+    If you loaded the simple module with from paraview.simple import *,
+    make sure to pass globals() as the second arguments:
+    LoadXML(xmlstring, globals())
+    Otherwise, the new functions will not appear in the global namespace."""
+    if not ns:
+        ns = globals()
+    servermanager.LoadXML(xmlstring)
+    _add_functions(ns)
+
+def LoadPlugin(filename, remote=True, ns=None):
+    """Loads a ParaView plugin and updates this module with new constructors
+    if any. The remote argument (default to True) is to specify whether 
+    the plugin will be loaded on client (remote=False) or on server (remote=True).
+    If you loaded the simple module with from paraview.simple import *,
+    make sure to pass globals() as an argument:
+    LoadPlugin("myplugin", False, globals()), to load on client;
+    LoadPlugin("myplugin", True, globals()), to load on server; 
+    LoadPlugin("myplugin", ns=globals()), to load on server.
+    Otherwise, the new functions will not appear in the global namespace."""
+    
+    if not ns:
+        ns = globals()
+    servermanager.LoadPlugin(filename, remote)
+    _add_functions(ns)
+
+class ActiveObjects(object):
+    """This class manages the active objects (source and view). The active
+    objects are shared between Python and the user interface. This class
+    is for internal use. Use the Set/Get methods for setting and getting
+    active objects."""
+    def __get_selection_model(self, name):
+        "Internal method."
+        pxm = servermanager.ProxyManager()
+        model = pxm.GetSelectionModel(name)
+        if not model:
+            model = servermanager.vtkSMProxySelectionModel()
+            pxm.RegisterSelectionModel(name, model)
+        return model
+
+    def set_view(self, view):
+        "Sets the active view."
+        active_view_model = self.__get_selection_model("ActiveView") 
+        if view:
+            active_view_model.SetCurrentProxy(view.SMProxy, 0)
+        else:
+            active_view_model.SetCurrentProxy(None, 0)
+
+    def get_view(self):
+        "Returns the active view."
+        return servermanager._getPyProxy(
+            self.__get_selection_model("ActiveView").GetCurrentProxy())
+
+    def set_source(self, source):
+        "Sets the active source."
+        active_sources_model = self.__get_selection_model("ActiveSources") 
+        if source:
+            # 3 == CLEAR_AND_SELECT
+            active_sources_model.SetCurrentProxy(source.SMProxy, 3)
+        else:
+            active_sources_model.SetCurrentProxy(None, 3)
+
+    def __convert_proxy(self, px):
+        "Internal method."
+        if not px:
+            return None
+        if px.IsA("vtkSMSourceProxy"):
+            return servermanager._getPyProxy(px)
+        else:
+            return servermanager.OutputPort(
+              servermanager._getPyProxy(px.GetSourceProxy()),
+              px.GetPortIndex())
+        
+    def get_source(self):
+        "Returns the active source."
+        return self.__convert_proxy(
+          self.__get_selection_model("ActiveSources").GetCurrentProxy())
+
+    def get_selected_sources(self):
+        "Returns the set of sources selected in the pipeline browser."
+        model = self.__get_selection_model("ActiveSources")
+        proxies = []
+        for i in xrange(model.GetNumberOfSelectedProxies()):
+            proxies.append(self.__convert_proxy(model.GetSelectedProxy(i)))
+        return proxies
+
+    view = property(get_view, set_view)
+    source = property(get_source, set_source)
+
+class _funcs_internals:
+    "Internal class."
+    first_render = True
+    view_counter = 0
+    rep_counter = 0
+
+def demo1():
+    """Simple demo that create the following pipeline
+    sphere - shrink - \
+                       - append
+    cone            - /
+    """
+    # Create a sphere of radius = 2, theta res. = 32
+    # This object becomes the active source.
+    ss = Sphere(Radius=2, ThetaResolution=32)
+    # Apply the shrink filter. The Input property is optional. If Input
+    # is not specified, the filter is applied to the active source.
+    shr = Shrink(Input=ss)
+    # Create a cone source.
+    cs = Cone()
+    # Append cone and shrink
+    app = AppendDatasets()
+    app.Input = [shr, cs]
+    # Show the output of the append filter. The argument is optional
+    # as the app filter is now the active object.
+    Show(app)
+    # Render the default view.
+    Render()
+
+def demo2(fname="/Users/berk/Work/ParaView/ParaViewData/Data/disk_out_ref.ex2"):
+    """This demo shows the use of readers, data information and display
+    properties."""
+    
+    # Create the exodus reader and specify a file name
+    reader = ExodusIIReader(FileName=fname)
+    # Get the list of point arrays.
+    avail = reader.PointVariables.Available
+    print avail
+    # Select all arrays
+    reader.PointVariables = avail
+
+    # Turn on the visibility of the reader
+    Show(reader)
+    # Set representation to wireframe
+    SetDisplayProperties(Representation = "Wireframe")
+    # Black background is not pretty
+    SetViewProperties(Background = [0.4, 0.4, 0.6])
+    Render()
+    # Change the elevation of the camera. See VTK documentation of vtkCamera
+    # for camera parameters.
+    # NOTE: THIS WILL BE SIMPLER
+    GetActiveCamera().Elevation(45)
+    Render()
+    # Now that the reader executed, let's get some information about it's
+    # output.
+    pdi = reader[0].PointData
+    # This prints a list of all read point data arrays as well as their
+    # value ranges.
+    print 'Number of point arrays:', len(pdi)
+    for i in range(len(pdi)):
+        ai = pdi[i]
+        print "----------------"
+        print "Array:", i, " ", ai.Name, ":"
+        numComps = ai.GetNumberOfComponents()
+        print "Number of components:", numComps
+        for j in range(numComps):
+            print "Range:", ai.GetRange(j)
+    # White is boring. Let's color the geometry using a variable.
+    # First create a lookup table. This object controls how scalar
+    # values are mapped to colors. See VTK documentation for
+    # details.
+    # Map min (0.00678) to blue, max (0.0288) to red
+    SetDisplayProperties(LookupTable = MakeBlueToRedLT(0.00678, 0.0288))
+    # Color by point array called Pres
+    SetDisplayProperties(ColorAttributeType = "POINT_DATA")
+    SetDisplayProperties(ColorArrayName = "Pres")
+    Render()
+
+def PrintTrace():
+    print paravisSM.myParavis.GetTrace()
+
+def SaveTrace(fileName):
+    paravisSM.myParavis.SaveTrace(fileName)
+
+
+_add_functions(globals())
+active_objects = ActiveObjects()
+## Initialisation for SALOME GUI
+active_objects.view = servermanager.GetRenderView()
+
+if not servermanager.ActiveConnection:
+    Connect()
diff --git a/src/PV_SWIG/servermanager.diff b/src/PV_SWIG/servermanager.diff
new file mode 100644 (file)
index 0000000..fbe8974
--- /dev/null
@@ -0,0 +1,304 @@
+29,55c29,35
+< #==============================================================================
+< #
+< #  Program:   ParaView
+< #  Module:    $RCSfile$
+< #
+< #  Copyright (c) Kitware, Inc.
+< #  All rights reserved.
+< #  See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
+< #
+< #     This software is distributed WITHOUT ANY WARRANTY without even
+< #     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+< #     PURPOSE.  See the above copyright notice for more information.
+< #
+< #==============================================================================
+< import paraview, re, os, new, sys, vtk
+< 
+< if not paraview.compatibility.minor:
+<     paraview.compatibility.major = 3
+< if not paraview.compatibility.major:
+<     paraview.compatibility.minor = 5
+< 
+< if os.name == "posix":
+<     from libvtkPVServerCommonPython import *
+<     from libvtkPVServerManagerPython import *
+< else:
+<     from vtkPVServerCommonPython import *
+<     from vtkPVServerManagerPython import *
+---
+> 
+> 
+> 
+> import re, os, new, sys
+> from paravis import *
+> 
+> 
+63,64c43
+<     if paraview.compatibility.GetVersion() >= 3.5 and \
+<       smproperty.IsA("vtkSMStringVectorProperty"):
+---
+>     if smproperty.IsA("vtkSMStringVectorProperty"):
+66,67c45
+<         if  al and al.IsA("vtkSMArraySelectionDomain") and \
+<             smproperty.GetRepeatable():
+---
+>         if  al and al.IsA("vtkSMArraySelectionDomain") and smproperty.GetRepeatable():
+87,88c65
+<         if smproperty.IsA("vtkSMIntVectorProperty") and \
+<           smproperty.GetDomain("enum"):
+---
+>         if smproperty.IsA("vtkSMIntVectorProperty") and smproperty.GetDomain("enum"):
+237,238c214,216
+<             return self.SMProxy == other.SMProxy
+<         return self.SMProxy == other
+---
+>             ## VSV using IsSame instead
+>             return self.SMProxy.IsSame(other.SMProxy)
+>         return self.SMProxy.IsSame(other)
+333,336c311,314
+<         if not c.HasObserver("ModifiedEvent"):
+<             self.ObserverTag =c.AddObserver("ModifiedEvent", \
+<                               _makeUpdateCameraMethod(weakref.ref(self)))
+<             self.Observed = c
+---
+>         # VSV: Observers are not supported
+> ##         if not c.HasObserver("ModifiedEvent"):
+> ##             self.ObserverTag =c.AddObserver("ModifiedEvent", _makeUpdateCameraMethod(weakref.ref(self)))
+> ##             self.Observed = c
+439,457c417,434
+<     if paraview.compatibility.GetVersion() >= 3.5:
+<         def FileNameChanged(self):
+<             "Called when the filename changes. Selects all variables."
+<             SourceProxy.FileNameChanged(self)
+<             self.SelectAllVariables()
+< 
+<         def SelectAllVariables(self):
+<             "Select all available variables for reading."
+<             for prop in ('PointVariables', 'EdgeVariables', 'FaceVariables',
+<                 'ElementVariables', 'GlobalVariables'):
+<                 f = getattr(self, prop)
+<                 f.SelectAll()
+< 
+<         def DeselectAllVariables(self):
+<             "Deselects all variables."
+<             for prop in ('PointVariables', 'EdgeVariables', 'FaceVariables',
+<                 'ElementVariables', 'GlobalVariables'):
+<                 f = getattr(self, prop)
+<                 f.DeselectAll()
+---
+>     def FileNameChanged(self):
+>         "Called when the filename changes. Selects all variables."
+>         SourceProxy.FileNameChanged(self)
+>         self.SelectAllVariables()
+> 
+>     def SelectAllVariables(self):
+>         "Select all available variables for reading."
+>         for prop in ('PointVariables', 'EdgeVariables', 'FaceVariables',
+>                      'ElementVariables', 'GlobalVariables'):
+>             f = getattr(self, prop)
+>             f.SelectAll()
+> 
+>     def DeselectAllVariables(self):
+>         "Deselects all variables."
+>         for prop in ('PointVariables', 'EdgeVariables', 'FaceVariables',
+>                      'ElementVariables', 'GlobalVariables'):
+>             f = getattr(self, prop)
+>             f.DeselectAll()
+1040c1017,1018
+<             if proxy == px:
+---
+>             ## VSV: ==
+>             if proxy.IsSame(px):
+1217c1195
+<         return vtk.vtkDataObjectTypes.GetClassNameFromTypeId(self.GetDataSetType())
+---
+>         return vtkDataObjectTypes.GetClassNameFromTypeId(self.GetDataSetType())
+1259,1261d1236
+<     if paraview.compatibility.GetVersion() <= 3.4:
+<        def Range(self, component=0):
+<            return self.GetRange(component)
+1521c1496
+<         collection = vtk.vtkCollection()
+---
+>         collection = vtkCollection()
+1844c1819,1820
+<     """Creates a new self connection.Internal method, use Connect() instead."""
+---
+>     """Initialises self connection.Internal method, use Connect() instead."""
+>     print "Connect to self"
+1909c1885
+< 
+---
+>        
+2015c1991,1992
+<         try: isRep = rep.Input == aProxy
+---
+>         #VSV: ==
+>         try: isRep = rep.Input.IsSame(aProxy)
+2261c2238,2239
+<     global progressObserverTag
+---
+>     pass
+>     #vsv global progressObserverTag
+2263,2270c2241,2248
+<     if fromGUI:
+<         raise RuntimeError, "Printing progress in the GUI is not supported."
+<     if progressObserverTag:
+<         vtkProcessModule.GetProcessModule().RemoveObserver(progressObserverTag)
+<         progressObserverTag = None
+<     else:
+<         progressObserverTag = vtkProcessModule.GetProcessModule().AddObserver(\
+<              "ProgressEvent", _printProgress)
+---
+>     #vsv if fromGUI:
+>     #vsv     raise RuntimeError, "Printing progress in the GUI is not supported."
+>     #vsv if progressObserverTag:
+>     #vsv     vtkProcessModule.GetProcessModule().RemoveObserver(progressObserverTag)
+>     #vsv     progressObserverTag = None
+>     #VSV Observer is not supported
+>     #else:
+>     #    progressObserverTag = vtkProcessModule.GetProcessModule().AddObserver("ProgressEvent", _printProgress)
+2273,2278c2251,2256
+<     """Although not required, this can be called at exit to cleanup."""
+<     global progressObserverTag
+<     # Make sure to remove the observer
+<     if progressObserverTag:
+<         ToggleProgressPrinting()
+<     vtkInitializationHelper.Finalize()
+---
+>    """Although not required, this can be called at exit to cleanup."""
+>    global progressObserverTag
+>    # Make sure to remove the observer
+>    if progressObserverTag:
+>        ToggleProgressPrinting()
+>    vtkInitializationHelper.Finalize()
+2293,2295c2271,2272
+<     if paraview.compatibility.GetVersion() >= 3.5:
+<         if smproxy.GetXMLLabel():
+<             xmlName = smproxy.GetXMLLabel()
+---
+>     if smproxy.GetXMLLabel():
+>         xmlName = smproxy.GetXMLLabel()
+2335,2338c2312
+<         if paraview.compatibility.GetVersion() >= 3.5:
+<             return self.GetPropertyValue(propName)
+<         else:
+<             return self.GetProperty(propName)
+---
+>         return self.GetPropertyValue(propName)
+2447c2421,2432
+<     return paraview.make_name_valid(name)
+---
+>     "Make a string into a valid Python variable name"
+>     if not name:
+>         return None
+>     if name.find('(') >= 0 or name.find(')') >=0:
+>         return None
+>     name = name.replace(' ','')
+>     name = name.replace('-','')
+>     name = name.replace(':','')
+>     name = name.replace('.','')
+>     if not name[0].isalpha():
+>         name = 'a' + name
+>     return name
+2465,2469c2450,2451
+<         if paraview.compatibility.GetVersion() >= 3.5:
+<             if proto.GetXMLLabel():
+<                 pname = proto.GetXMLLabel()
+<         else:
+<             pname = proxyName
+---
+>         if proto.GetXMLLabel():
+>             pname = proto.GetXMLLabel()
+2483,2486c2465,2466
+<             if paraview.compatibility.GetVersion() >= 3.5:
+<                 if (prop.GetInformationOnly() and propName != "TimestepValues" ) \
+<                   or prop.GetIsInternal():
+<                     continue
+---
+>             if (prop.GetInformationOnly() and propName != "TimestepValues" ) or prop.GetIsInternal():
+>                 continue
+2488,2489c2468
+<             if paraview.compatibility.GetVersion() >= 3.5:
+<                 names = [iter.PropertyLabel]
+---
+>             names = [iter.PropertyLabel]
+2502,2503c2481
+<         if proto.GetDocumentation() and \
+<            proto.GetDocumentation().GetDescription():
+---
+>         if proto.GetDocumentation() and proto.GetDocumentation().GetDescription():
+2505,2506c2483,2484
+<         else:
+<             doc = Proxy.__doc__
+---
+>         #else:
+>         doc = Proxy.__doc__
+2616,2625c2594,2597
+<     if paraview.compatibility.GetVersion() <= 3.4:
+<         ss = sources.SphereSource(Radius=2, ThetaResolution=32)
+<         shr = filters.ShrinkFilter(Input=OutputPort(ss,0))
+<         cs = sources.ConeSource()
+<         app = filters.Append()
+<     else:
+<         ss = sources.Sphere(Radius=2, ThetaResolution=32)
+<         shr = filters.Shrink(Input=OutputPort(ss,0))
+<         cs = sources.Cone()
+<         app = filters.AppendDatasets()
+---
+>     ss = sources.Sphere(Radius=2, ThetaResolution=32)
+>     shr = filters.Shrink(Input=OutputPort(ss,0))
+>     cs = sources.Cone()
+>     app = filters.AppendDatasets()
+2646,2649c2618
+<     if paraview.compatibility.GetVersion() <= 3.4:
+<         arraySelection = reader.PointResultArrayStatus
+<     else:
+<         arraySelection = reader.PointVariables
+---
+>     arraySelection = reader.PointVariables
+2683,2686c2652
+<             if paraview.compatibility.GetVersion() <= 3.4:
+<                 print "Range:", ai.Range(j)
+<             else:
+<                 print "Range:", ai.GetRange(j)
+---
+>             print "Range:", ai.GetRange(j)
+2717,2720c2683
+<     if paraview.compatibility.GetVersion() <= 3.4:
+<         source = sources.RTAnalyticSource()
+<     else:
+<         source = sources.Wavelet()
+---
+>     source = sources.Wavelet()
+2751,2758c2714,2716
+<     if paraview.compatibility.GetVersion() <= 3.4:
+<         probe = filters.Probe(Input=source)
+<         # with a line
+<         line = sources.LineSource(Resolution=60)
+<     else:
+<         probe = filters.ResampleWithDataset(Input=source)
+<         # with a line
+<         line = sources.Line(Resolution=60)
+---
+>     probe = filters.ResampleWithDataset(Input=source)
+>     # with a line
+>     line = sources.Line(Resolution=60)
+2802,2805c2760
+<     if paraview.compatibility.GetVersion() <= 3.4:
+<         sphere = sources.SphereSource()
+<     else:
+<         sphere = sources.Sphere()
+---
+>     sphere = sources.Sphere()
+2871a2827,2833
+> # Definitions for working in SALOME GUI mode
+> aParams = myParavis.GetConnectionParameters()
+> ActiveConnection = Connection(aParams[0])
+> ActiveConnection.SetHost(aParams[1], aParams[2], aParams[3], aParams[4], aParams[5])
+> ToggleProgressPrinting()
+> fromGUI = True
+> 
+2872a2835
+> 
diff --git a/src/PV_SWIG/simple.diff b/src/PV_SWIG/simple.diff
new file mode 100644 (file)
index 0000000..ed0df8a
--- /dev/null
@@ -0,0 +1,51 @@
+21,39c21,24
+< #==============================================================================
+< #
+< #  Program:   ParaView
+< #  Module:    $RCSfile$
+< #
+< #  Copyright (c) Kitware, Inc.
+< #  All rights reserved.
+< #  See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
+< #
+< #     This software is distributed WITHOUT ANY WARRANTY; without even
+< #     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+< #     PURPOSE.  See the above copyright notice for more information.
+< #
+< #==============================================================================
+< 
+< import paraview
+< paraview.compatibility.major = 3
+< paraview.compatibility.minor = 5
+< import servermanager
+---
+> 
+> import paravisSM
+> 
+> servermanager = paravisSM
+259c244,245
+<         if proxy == GetActiveSource():
+---
+>         #VSV:==
+>         if proxy.IsSame(GetActiveSource()):
+267c253,254
+<             if rep.Input == proxy:
+---
+>             #VSV:==
+>             if rep.Input.IsSame(proxy):
+271c258,259
+<         if proxy == GetActiveView():
+---
+>         ##VSV:==
+>         if proxy.IsSame(GetActiveView()):
+679a668,674
+> def PrintTrace():
+>     print paravisSM.myParavis.GetTrace()
+> 
+> def SaveTrace(fileName):
+>     paravisSM.myParavis.SaveTrace(fileName)
+> 
+> 
+681a677,678
+> ## Initialisation for SALOME GUI
+> active_objects.view = servermanager.GetRenderView()
diff --git a/test/MedData/BoxHexa2.med b/test/MedData/BoxHexa2.med
new file mode 100755 (executable)
index 0000000..9653f1f
Binary files /dev/null and b/test/MedData/BoxHexa2.med differ
diff --git a/test/Pic/Information.txt b/test/Pic/Information.txt
new file mode 100644 (file)
index 0000000..0519ecb
--- /dev/null
@@ -0,0 +1 @@
\ No newline at end of file
diff --git a/test/demo0.py b/test/demo0.py
new file mode 100755 (executable)
index 0000000..0237e78
--- /dev/null
@@ -0,0 +1,139 @@
+""" This module can be used to run a simple rendering benchmark test. This
+test renders a sphere with various rendering settings and reports the rendering
+rate achieved in triangles/sec. """
+
+if not ('servermanager' in dir()):
+  from pvsimple import *
+
+import time, sys, os
+
+def render(ss, v, title, nframes):
+  print '============================================================'
+  print title
+  res = []
+  res.append(title)
+  for phires in (500, 1000):
+    ss.PhiResolution = phires
+    c = v.GetActiveCamera()
+    v.CameraPosition = [-3, 0, 0]
+    v.CameraViewUp = [0, 0, 1]
+    v.StillRender()
+    c1 = time.time()
+    for i in range(nframes):
+      c.Elevation(0.5)
+      v.StillRender()
+      sys.stdout.write(".")
+      sys.stdout.write("\n")
+    tpr = (time.time() - c1)/nframes
+    ncells = ss.GetDataInformation().GetNumberOfCells()
+    print tpr, " secs/frame"
+    print ncells, " polys"
+    print ncells/tpr, " polys/sec"
+    
+    res.append((ncells, ncells/tpr))
+
+  return res
+
+def run(filesour, impth, nframes):
+
+  """ Runs the benchmark. If a filename is specified, it will write the
+  results to that file as csv. The number of frames controls how many times
+  a particular configuration is rendered. Higher numbers lead to more accurate
+  averages. """
+
+  # Create a sphere source to use in the benchmarks
+  ss = Sphere(Radius=0.5, ThetaResolution=32, PhiResolution=8)
+
+  # The view and representation
+  v = GetRenderView()
+  if not v:
+    v = CreateRenderView()
+  rep = None
+  rep = GetRepresentation(proxy=None, view=v)
+  results = []
+
+  # Start with these defaults
+  v.UseImmediateMode = 0
+  v.UseTriangleStrips = 0
+  
+  # Test different configurations
+  title = 'display lists, no triangle strips, solid color'
+  v.UseImmediateMode = 0
+  v.UseTriangleStrips = 0
+  results.append(render(ss, v, title, nframes))
+  WriteImage(filename = (impth + "demo0_1.png"), view=v, Magnification=2)
+
+  title = 'display lists, triangle strips, solid color'
+  v.UseTriangleStrips = 1
+  results.append(render(ss, v, title, nframes))
+  #WriteImage(filename = (impth + "demo0_2.png"), view=v, Magnification=2)
+
+  title = 'no display lists, no triangle strips, solid color'
+  v.UseImmediateMode = 1
+  v.UseTriangleStrips = 0
+  results.append(render(ss, v, title, nframes))
+  #WriteImage(filename = (impth + "demo0_3.png"), view=v, Magnification=2)
+
+  title = 'no display lists, triangle strips, solid color'
+  v.UseTriangleStrips = 1
+  results.append(render(ss, v, title, nframes))
+  #WriteImage(filename = (impth + "demo0_4.png"), view=v, Magnification=2)
+
+  # Color by normals
+  lt = MakeBlueToRedLT(-1, 1)
+  rep.LookupTable = lt
+  rep.ColorAttributeType = 0 # point data
+  rep.ColorArrayName = "Normals"
+  lt.RGBPoints = [-1, 0, 0, 1, 0.0288, 1, 0, 0]
+  lt.ColorSpace = 1 # HSV
+  lt.VectorComponent = 0
+  
+  title = 'display lists, no triangle strips, color by array'
+  v.UseImmediateMode = 0
+  v.UseTriangleStrips = 0
+  results.append(render(ss, v, title, nframes))
+  #WriteImage(filename = (impth + "demo0_5.png"), view=v, Magnification=2)
+
+  title = 'display lists, triangle strips, color by array'
+  v.UseTriangleStrips = 1
+  results.append(render(ss, v, title, nframes))
+  v.UseImmediateMode = 1
+  #WriteImage(filename = (impth + "demo0_6.png"), view=v, Magnification=2)
+
+  title = 'no display lists, no triangle strips, color by array'
+  v.UseImmediateMode = 1
+  v.UseTriangleStrips = 0
+  results.append(render(ss, v, title, nframes))
+  #WriteImage(filename = (impth + "demo0_7.png"), view=v, Magnification=2)
+
+  title = 'no display lists, triangle strips, color by array'
+  v.UseTriangleStrips = 1
+  results.append(render(ss, v, title, nframes))
+  WriteImage(filename = (impth + "demo0_8.png"), view=v, Magnification=2)
+
+  newr = []
+  for r in v.Representations:
+   if r != rep:
+     newr.append(r)
+   v.Representations = newr
+  
+  ss = None
+  rep = None
+  
+  v.StillRender()
+  v = None
+
+  if filesour:
+    f = open(filesour, "w")
+  else:
+    f = sys.stdout
+  print >>f, 'configuration, %d, %d' % (results[0][1][0], results[0][2][0])
+  for i in results:
+    print >>f, '"%s", %g, %g' % (i[0], i[1][1], i[2][1])  
+
+
+testdir = os.getenv("TESTDIR")
+pvdata = os.getenv("PVDATA")
+
+if __name__ == "__main__":
+  run(filesour=testdir + "/Pic/Information.txt", impth=testdir + "/Pic/", nframes=10)
diff --git a/test/demo1.py b/test/demo1.py
new file mode 100755 (executable)
index 0000000..e7d6632
--- /dev/null
@@ -0,0 +1,54 @@
+if not ('servermanager' in dir()):
+  from pvsimple import *
+
+import os
+
+def demo1(impth):
+    """Simple demo that create the following pipeline
+    sphere - shrink - \
+                       - append
+    cone            - /
+    """
+
+    # Create a sphere of radius = 0.5, theta res. = 32
+    # This object becomes the active source.
+    ss = Sphere(Radius=0.5, ThetaResolution=32, PhiResolution=8)
+
+    # The view and representation
+    v = GetRenderView()
+    if not v:
+       v = CreateRenderView()
+    v.CameraPosition = [-3, -3, -3]
+    v.CameraViewUp = [0, 0, 1]
+    v.StillRender()
+
+    # Apply the shrink filter. The Input property is optional. If Input
+    # is not specified, the filter is applied to the active source.
+    shr = Shrink(Input=ss)
+    # Create a cone source. 
+    cs = Cone()
+
+    # Append cone and shrink
+    app = AppendDatasets()
+    app.Input = [shr, cs]
+
+    # Show the output of the append filter. The argument is optional
+    # as the app filter is now the active object.
+    Show(app)
+    WriteImage(filename = (impth + "demo1_1.png"), view=v, Magnification=2) 
+
+    PointData = app.GetDataInformation().GetNumberOfPoints()
+    CellData = app.GetDataInformation().GetNumberOfCells()
+    print PointData, " Points"
+    print CellData, " Cells"
+
+    # Render the default view.
+    Render()
+
+    
+testdir = os.getenv("TESTDIR")
+pvdata = os.getenv("PVDATA")
+
+if __name__ == "__main__":
+  demo1(impth =testdir+"/Pic/")
diff --git a/test/demo10.py b/test/demo10.py
new file mode 100755 (executable)
index 0000000..2c1cbd4
--- /dev/null
@@ -0,0 +1,64 @@
+
+if not ('servermanager' in dir()):
+  from pvsimple import *
+
+import os
+
+def demo10(fname, impth):
+    """This method demonstrates the Contour filter."""
+
+    reader = ExodusIIReader(FileName=fname)
+    v=GetActiveView()
+    ##Show(reader, view=v)
+    contourFilter = Contour(reader)
+    contourFilter.ContourBy = 'Temp'
+    contourFilter.Isosurfaces
+    ##[]
+
+    contourFilter.Isosurfaces = [400]
+    camera = GetActiveCamera()
+    camera.Position = [0., 60., -33]
+    camera.Elevation(-70)
+    dp2 = GetDisplayProperties(contourFilter)
+    contourFilter.PointData[:]
+    ##[Array: Temp, Array: V, Array: Pres, Array: AsH3, Array: GaMe3, Array: CH4, Array: H2]
+
+    temp = contourFilter.PointData[0]
+    temp.GetRange()
+    ## (399.99999999999994, 400.00000000000006)
+
+    dp2.LookupTable = MakeBlueToRedLT(399.999,400)
+    dp2.ColorAttributeType = 'POINT_DATA'
+    dp2.ColorArrayName = 'Temp'
+    Render()
+    WriteImage(filename = (impth + "contourFilter_1.png"), view=v, Magnification=2)
+
+    pres = contourFilter.PointData[2]
+    pres.GetRange()
+    ##(0.0074376024368978605, 0.02845284189526591)
+
+    dp2.LookupTable = MakeBlueToRedLT(0.007437602, 0.02845284)
+    dp2.ColorArrayName = 'Pres'
+    Render()
+    WriteImage(filename = (impth + "contourFilter_2.png"), view=v, Magnification=2)
+
+    dp1 = GetDisplayProperties(reader)
+    dp1.Representation = 'Wireframe'
+    dp1.LookupTable = dp2.LookupTable
+    dp1.ColorAttributeType = 'POINT_DATA'
+    dp1.ColorArrayName = 'Pres'
+    Show(reader)
+    camera.Dolly(0.5)
+    Render()
+    camera.Elevation(-150)
+    Render()
+    WriteImage(filename = (impth + "contourFilter_3.png"), view=v, Magnification=2)
+
+    
+testdir = os.getenv("TESTDIR")
+pvdata = os.getenv("PVDATA")
+
+if __name__ == "__main__":
+ demo10(fname=pvdata+"/Data/disk_out_ref.ex2", impth=testdir+"/Pic/")
diff --git a/test/demo11.py b/test/demo11.py
new file mode 100755 (executable)
index 0000000..dd05243
--- /dev/null
@@ -0,0 +1,60 @@
+
+if not ('servermanager' in dir()):
+  from pvsimple import *
+
+import os
+
+def demo11(fname, impth):
+    """This method demonstrates the Contour filter."""
+
+    reader = ExodusIIReader(FileName=fname)
+    v=GetActiveView()
+    clipFilter = Clip(reader)
+    clipFilter.ClipType = 'Scalar'
+    clipFilter.Scalars = 'Temp'
+    clipFilter.Value = 400
+    Show(clipFilter)
+    camera = GetActiveCamera()
+    camera.Elevation(-75)
+    Render()
+    WriteImage(filename = (impth + "clipFilter_1.png"), view=v, Magnification=2)
+
+    clipFilter2 = Clip(clipFilter)
+    Show(clipFilter2)
+    Hide(clipFilter)
+    camera.SetPosition(-39, 0, 1.46)
+    camera.Roll(90)
+    WriteImage(filename = (impth + "clipFilter_2.png"), view=v, Magnification=2)
+
+    dp1 = GetDisplayProperties(reader)
+    dp2 = GetDisplayProperties(clipFilter2)
+    clipFilter2.PointData[:]
+    ##[Array: Temp, Array: V, Array: Pres, Array: AsH3, Array: GaMe3, Array: CH4, Array: H2]
+
+    temp = clipFilter2.PointData[0]
+    temp.GetRange()
+    ##(399.99999999999994, 913.1500244140625)
+
+    dp2.LookupTable = MakeBlueToRedLT(400,913.15)
+    dp2.ColorAttributeType = 'POINT_DATA'
+    dp2.ColorArrayName = 'Temp'
+    Hide(reader)
+    Render()
+    WriteImage(filename = (impth + "clipFilter_3.png"), view=v, Magnification=2)
+
+    dp1.Representation = 'Volume'
+    temp.GetRange()
+    ##(399.99999999999994, 913.1500244140625)
+    dp1.LookupTable = dp2.LookupTable
+    dp1.ColorAttributeType = 'POINT_DATA'
+    dp1.ColorArrayName = 'Temp'
+    Show(reader)
+    Render()
+    WriteImage(filename = (impth + "clipFilter_4.png"), view=v, Magnification=2)
+
+testdir = os.getenv("TESTDIR")
+pvdata = os.getenv("PVDATA")
+
+if __name__ == "__main__":
+ demo11(fname=pvdata+"/Data/disk_out_ref.ex2", impth=testdir+"/Pic/")
diff --git a/test/demo12.py b/test/demo12.py
new file mode 100755 (executable)
index 0000000..b6533be
--- /dev/null
@@ -0,0 +1,37 @@
+
+if not ('servermanager' in dir()):
+  from pvsimple import *
+
+import os
+
+def demo12(fname, impth):
+    """This method demonstrates the Stream Tracer."""
+
+    reader = ExodusIIReader(FileName=fname)
+    v=GetActiveView()
+    streamTracer = StreamTracer(reader)
+    streamTracer.Vectors  = 'V'
+    streamTracer.SeedType.NumberOfPoints = 100
+    streamTracer.SeedType.Radius = 1.15
+    streamTracer.MaximumStreamlineLength = 25.
+
+    Show(streamTracer)
+    camera = GetActiveCamera()
+    camera.Elevation(-45)
+    camera.Dolly(0.4)
+    dp1 = GetDisplayProperties(streamTracer)
+    streamTracer.PointData[:]
+    ##[Array: Temp, Array: V, Array: Pres, Array: AsH3, Array: GaMe3, Array: CH4, Array: H2, Array: IntegrationTime, Array: Vorticity, Array: Rotation,     ##Array: AngularVelocity, Array: Normals]
+    
+    pres = streamTracer.PointData[2]
+    dp1.LookupTable = MakeBlueToRedLT(pres.GetRange()[0],pres.GetRange()[1])
+    dp1.ColorAttributeType = 'POINT_DATA'
+    dp1.ColorArrayName = 'Pres'
+    Render()
+    WriteImage(filename = (impth + "streamTracer_1.png"), view=v, Magnification=2)
+
+testdir = os.getenv("TESTDIR")
+pvdata = os.getenv("PVDATA")
+
+if __name__ == "__main__":
+ demo12(fname=pvdata+"/Data/disk_out_ref.ex2", impth=testdir+"/Pic/")
diff --git a/test/demo2.py b/test/demo2.py
new file mode 100755 (executable)
index 0000000..2c591fc
--- /dev/null
@@ -0,0 +1,83 @@
+
+if not ('servermanager' in dir()):
+  from pvsimple import *
+
+import os
+
+def demo2(fname, impth):
+    """This demo shows the use of readers, data information and display properties."""
+   
+ # The view
+    v = GetRenderView()
+    if not v:
+       v = CreateRenderView()
+    v.CameraPosition = [-20, -9, -45]
+    v.CameraFocalPoint = [0.7, 0.3, 1.7]
+    v.CameraViewUp = [-0.75, -0.6, 0.25]
+    v.CameraViewAngle = [30]
+    v.StillRender()
+
+    # Create the exodus reader and specify a file name
+    reader = ExodusIIReader(FileName=fname)
+
+    # Get the list of point arrays.
+    avail = reader.PointVariables.Available
+    print avail
+
+    # Select all arrays
+    reader.PointVariables = avail
+
+    # Turn on the visibility of the reader
+    Show(reader)
+
+    # Set representation to wireframe
+    SetDisplayProperties(Representation = "Wireframe")
+   
+    # Black background
+    SetViewProperties(Background = [0., 0., 0.])
+    Render()
+
+    # Change the elevation of the camera.
+    GetActiveCamera().Elevation(45)
+    Render()
+
+    # Now that the reader executed, let's get some information about it's output.
+    pdi = reader[0].PointData
+
+    # This prints a list of all read point data arrays as well as their value ranges.
+    print 'Number of point arrays:', len(pdi)
+    for i in range(len(pdi)):
+        ai = pdi[i]
+        print "----------------"
+        print "Array:", i, " ", ai.Name, ":"
+        numComps = ai.GetNumberOfComponents()
+        print "Number of components:", numComps
+        for j in range(numComps):
+            print "Range:", ai.GetRange(j)
+
+    # White is boring. Let's color the geometry using a variable. First create a lookup table. This object controls how scalar values are mapped to colors. 
+    SetDisplayProperties(LookupTable = MakeBlueToRedLT(0.00678, 0.0288))
+
+    # Color by point array called Pres
+    SetDisplayProperties(ColorAttributeType = "POINT_DATA")
+    SetDisplayProperties(ColorArrayName = "Pres")
+
+    WriteImage(filename = (impth + "demo2_1.png"), view=v, Magnification=2)
+
+    # Set representation to surface
+    SetDisplayProperties(Representation = "Surface")
+
+    # Scalar Bar
+    lt = MakeBlueToRedLT(0.00678, 0.0288)
+    ScalarBar = CreateScalarBar(LookupTable = lt, Title = "Sample")
+    GetRenderView().Representations.append(ScalarBar)
+    WriteImage(filename = (impth + "demo2_2.png"), view=v, Magnification=2)
+    Render()
+
+
+testdir = os.getenv("TESTDIR")
+pvdata = os.getenv("PVDATA")
+
+if __name__ == "__main__":
+ demo2(fname=pvdata+"/Data/disk_out_ref.ex2", impth=testdir+"/Pic/")
+
diff --git a/test/demo3.py b/test/demo3.py
new file mode 100755 (executable)
index 0000000..344652f
--- /dev/null
@@ -0,0 +1,78 @@
+
+if not ('servermanager' in dir()):
+  from pvsimple import *
+
+import  os
+
+def demo3(impth):
+    """This method demonstrates an artificial data sources,
+    probes it with a line, etc"""
+
+    # The TWO views
+    rv = GetRenderView()
+    
+    v = CreateRenderView()  
+    v.CameraPosition = [-30, -20, -65]
+    v.CameraFocalPoint = [0.0, 0.0, 0.0]
+    v.CameraViewUp = [-0.65, -0.55, 0.5]
+    v.CameraViewAngle = [30]
+    SetActiveView(rv)
+
+    src = Wavelet()
+    # Get some information about the data. First, for the source to execute
+    UpdatePipeline()
+
+    di = src.GetDataInformation()
+    print "Data type:", di.GetPrettyDataTypeString()
+    print "Extent:", di.GetExtent()
+
+    ##src.Representation = 3 # outline
+    Show(src, view=v)
+    v.StillRender()
+
+    # Apply a contour filter
+    cf = Contour(Input = src)
+    cf.ContourBy = ['POINTS', 'RTData']
+    cf.Isosurfaces = [37.353099999999998, 63.961533333333335, 90.569966666666673, 117.1784, 143.78683333333333, 170.39526666666666, 
+                                 197.00370000000001, 223.61213333333333, 250.22056666666668, 276.82900000000001]
+    Show(cf, view=rv)
+
+    #Set background
+    SetViewProperties(Background = [.50, .20, .30])
+    Render()
+
+    # Reset the camera to include the whole thing
+    rv.StillRender()
+    rv.ResetCamera()
+    rv.CameraPosition = [-2.50, 60, -40]
+    rv.CameraFocalPoint = [1.25, 1.0, 1.35]
+    rv.CameraViewUp = [-0.955, 0.1, 0.25]
+    rv.CameraViewAngle = [30]
+    rv.StillRender()
+
+    # Now, let's probe the data
+    probe = ResampleWithDataset(Input=src)
+
+    # with a line
+    line = Line(Resolution=60)
+
+    # that spans the dataset
+    bounds = di.GetBounds()
+
+    print "Bounds: ", bounds
+    line.Point1 = bounds[0:6:2]
+    line.Point2 = bounds[1:6:2]
+
+    probe.Source = line
+
+    # Render with the line
+    Show(line, view=rv)
+    rv.StillRender()
+    WriteImage(filename = (impth + "demo3_1.png"), view=v, Magnification=2)
+    WriteImage(filename = (impth + "demo3_2.png"), view=rv, Magnification=2)
+
+testdir = os.getenv("TESTDIR")
+pvdata = os.getenv("PVDATA")
+
+if __name__ == "__main__":
+ demo3(impth=testdir+"/Pic/")
diff --git a/test/demo4.py b/test/demo4.py
new file mode 100755 (executable)
index 0000000..4b8d650
--- /dev/null
@@ -0,0 +1,30 @@
+
+if not ('servermanager' in dir()):
+  from pvsimple import *
+
+import os
+
+def demo4(fname, animpth):
+    """This method demonstrates the AnimateReader for creating animations."""
+
+    reader = ExodusIIReader(FileName=fname)
+    v = CreateRenderView()
+    repr = Show(reader, view=v)
+    v.StillRender()
+    v.ResetCamera()
+    ##v.CameraPosition = [0., -30, 0]
+    ##v.CameraFocalPoint = [6.2, 9.5, -0.5]
+    ##v.CameraViewUp = [-0.64, 0.2, -0.75]
+    ##v.CameraViewAngle = [30]
+    v.StillRender()
+    c = v.GetActiveCamera()
+    c.Elevation(95)
+  
+    r = AnimateReader(reader, view=v, filename=(animpth + "can.png"))
+
+
+testdir = os.getenv("TESTDIR")
+pvdata = os.getenv("PVDATA")
+
+if __name__ == "__main__":
+ demo4(fname=pvdata+"/Data/can.ex2", animpth=testdir+"/Animation/")
diff --git a/test/demo5.py b/test/demo5.py
new file mode 100755 (executable)
index 0000000..89db63b
--- /dev/null
@@ -0,0 +1,53 @@
+
+if not ('servermanager' in dir()):
+  from pvsimple import *
+
+import os
+
+def LoadMultipleFiles(FilePath, FilePrefix):
+
+  dualSphereAnimation = XMLPolyDataReader( FileName=[FilePath + FilePrefix + '0' + '.vtp',
+                                                                                                     FilePath + FilePrefix + '1' + '.vtp',
+                                                                                                     FilePath + FilePrefix + '2' + '.vtp',
+                                                                                                     FilePath + FilePrefix + '3' + '.vtp',
+                                                                                                     FilePath + FilePrefix + '4' + '.vtp',
+                                                                                                     FilePath + FilePrefix + '5' + '.vtp',
+                                                                                                     FilePath + FilePrefix + '6' + '.vtp',
+                                                                                                     FilePath + FilePrefix + '7' + '.vtp',
+                                                                                                     FilePath + FilePrefix + '8' + '.vtp',
+                                                                                                     FilePath + FilePrefix + '9' + '.vtp',
+                                                                                                     FilePath + FilePrefix + '10' + '.vtp'])
+
+  dualSphereAnimation.PointArrayStatus = ['Normals']
+  dualSphereAnimation.CellArrayStatus = ['cellNormals']
+
+  DataRepr = Show()
+  DataRepr.EdgeColor = [0.0, 0.0, 0.50000762951094835]
+  DataRepr.SelectionCellLabelColor = [0.0, 1.0, 0.0]
+  DataRepr.SelectionPointLabelJustification = 'Center'
+  DataRepr.SelectionCellLabelJustification = 'Center'
+  DataRepr.SelectionLineWidth = 2.0
+  DataRepr.SelectionCellLabelFontSize = 24
+  DataRepr.SelectionColor = [1.0, 0.0, 1.0]
+  DataRepr.SelectionRepresentation = 'Wireframe'
+
+  RenderV = GetRenderView()
+  RenderV.CameraViewUp = [0.3643594701432189, -0.53089863872031573, -0.76510705912432175]
+  RenderV.CameraPosition = [-1.43673886826885, 0.58420580818614165, -1.2056476292046452]
+  RenderV.CameraClippingRange = [1.1902279246461551, 3.3614292621569204]
+  RenderV.CameraFocalPoint = [0.24373197555541973, 4.2615454220042359e-08, -1.2218938645261819e-16]
+  RenderV.CameraParallelScale = 0.5562421018838376
+  RenderV.CenterOfRotation = [0.24373197555541992, 4.2615454276528908e-08, 0.0]
+  RenderV.CameraViewUp = [-0.022295256951954404, 0.99334037123472696, -0.11303905693476472]
+  RenderV.CameraFocalPoint = [0.24373197555541956, 4.261545421741021e-08, 6.2953480785622502e-17]
+  RenderV.CameraClippingRange = [0.8880289667943051, 3.8672572119597652]
+  RenderV.CameraPosition = [0.73282076784458949, 0.24745673087950623, 2.078081369909921]
+
+  Render()
+
+
+testdir = os.getenv("TESTDIR")
+pvdata = os.getenv("PVDATA")
+
+if __name__ == "__main__":
+  LoadMultipleFiles(FilePath=pvdata+"/Data/dualSphereAnimation/", FilePrefix="dualSphereAnimation_P00T000")
diff --git a/test/demo6.py b/test/demo6.py
new file mode 100755 (executable)
index 0000000..ebd3b9f
--- /dev/null
@@ -0,0 +1,56 @@
+
+if not ('servermanager' in dir()):
+  from pvsimple import *
+
+import os
+
+def demo6(fname, impth):
+    """This method demonstrates the Clip filter."""
+
+    reader = ExodusIIReader(FileName=fname)
+    v = CreateRenderView()
+    repr = Show(reader, view=v)
+    Render()
+    v.StillRender()
+    v.ResetCamera()
+    clipFilter = Clip(reader)
+    Hide(reader)
+    Show(clipFilter)
+    Render()
+
+    #get camera
+    camera = GetActiveCamera()
+    camera.GetPosition()
+
+    #figure out where you are
+    camera.SetPosition(4.156,4.0,-36.29)
+    camera.Elevation(30)
+    camera.SetPosition(4.15603, 30, -35)
+    Render()
+    clipFilter.UseValueAsOffset = 1
+    clipFilter.Value = 5
+    Render()
+    WriteImage(filename = (impth + "clipFilter_1.png"), view=v, Magnification=2)
+
+    clipFilter.ClipType.Normal
+    clipFilter.ClipType.Origin
+
+    #reset the offset value of the clip to 0
+    clipFilter.Value = 0
+    clipFilter.ClipType.Normal = [0, 0, 1]
+    Render()
+    WriteImage(filename = (impth + "clipFilter_2.png"), view=v, Magnification=2)
+
+    clipFilter.Value = -3
+    Render()
+    WriteImage(filename = (impth + "clipFilter_3.png"), view=v, Magnification=2)
+
+    clipFilter.InsideOut = 1
+    Render()
+    WriteImage(filename = (impth + "clipFilter_4.png"), view=v, Magnification=2)
+
+testdir = os.getenv("TESTDIR")
+pvdata = os.getenv("PVDATA")
+
+if __name__ == "__main__":
+ demo6(fname=pvdata+"/Data/can.ex2", impth=testdir+"/Pic/")
diff --git a/test/demo7.py b/test/demo7.py
new file mode 100755 (executable)
index 0000000..c13d89d
--- /dev/null
@@ -0,0 +1,45 @@
+
+if not ('servermanager' in dir()):
+  from pvsimple import *
+
+import os
+
+def demo7(fname, impth):
+    """This method demonstrates the Slice filter."""
+
+    v=GetActiveView()
+    reader = ExodusIIReader(FileName=fname)
+    sliceFilter = Slice(reader)
+    Show(sliceFilter)
+    Render()
+   
+    camera = GetActiveCamera()
+    camera.Elevation(30)
+    camera.SetPosition(17, 40, -25)
+    Render()
+    WriteImage(filename = (impth + "sliceFilter_1.png"), view=v, Magnification=2)
+
+    sliceFilter.SliceType.Normal
+
+    #The origin of the slice needs to be moved to see slices in the Y-plane
+    sliceFilter.SliceType.Origin = [2.5,5,0]
+    sliceFilter.SliceType.Normal = [0,1,0]
+    Render()
+    WriteImage(filename = (impth + "sliceFilter_2.png"), view=v, Magnification=2)
+
+    sliceFilter.SliceType.Normal = [0,0,1]
+    Render()
+    WriteImage(filename = (impth + "sliceFilter_3.png"), view=v, Magnification=2)
+
+    sliceFilter.SliceType.Normal = [0,1,0]
+    sliceFilter.SliceOffsetValues
+    sliceFilter.SliceOffsetValues = [-4,-3.11,-2.22,-1.33,-0.44,0.44,1.33,2.22,3.11,4]
+
+    Render()
+    WriteImage(filename = (impth + "sliceFilter_4.png"), view=v, Magnification=2)
+
+testdir = os.getenv("TESTDIR")
+pvdata = os.getenv("PVDATA")
+
+if __name__ == "__main__":
+ demo7(fname=pvdata+"/Data/can.ex2", impth=testdir+"/Pic/")
diff --git a/test/demo8.py b/test/demo8.py
new file mode 100755 (executable)
index 0000000..507f723
--- /dev/null
@@ -0,0 +1,65 @@
+
+if not ('servermanager' in dir()):
+  from pvsimple import *
+
+import os
+
+def demo8(fname, impth):
+    """This method demonstrates the Glyph filter."""
+
+    reader = ExodusIIReader(FileName=fname)
+    v=GetActiveView()
+    Show(reader, view=v)
+    camera = GetActiveCamera()
+    camera.SetPosition(0, 5, -45)
+    camera.Elevation(30)
+
+    #Change the can to be wireframe so we can see the glyphs
+    dp1 = GetDisplayProperties(reader, view=v)
+    dp1.Representation = 'Wireframe'
+    glyphFilter = Glyph(reader)
+
+    #We won't see much if we don't move forward in the animation a little bit
+    tsteps = reader.TimestepValues
+    v = GetActiveView()
+    v.ViewTime = tsteps[20]
+    glyphFilter.Vectors
+    ## ['POINTS', 'DISPL']
+
+    #Set the glyphs to use the acceleration vectors and adjust scale factor
+    glyphFilter.Vectors = 'ACCL'
+    ##glyphFilter.GetScaleFactor
+    ##1.0
+    glyphFilter.SetScaleFactor = 0.0000002
+    
+    Show()
+    Render()
+    WriteImage(filename = (impth + "glyphFilter_1.png"), view=v, Magnification=2)
+
+    #Set the glyphs to use the velocity vectors and adjust scale factor
+    glyphFilter.Vectors = 'VEL'
+    glyphFilter.SetScaleFactor = 3e-4
+    #Add some color
+    dp2 = GetDisplayProperties(glyphFilter)
+    glyphFilter.PointData[:]
+    ##[Array: PedigreeNodeId, Array: DISPL, Array: VEL, Array: ACCL, Array: GlobalNodeId, Array: GlyphVector]
+
+    #We'll color by velocity so use that array.
+    vel = glyphFilter.PointData[2]
+    vel.GetName()
+    ##'VEL'
+
+    vel.GetRange()
+    ##(-2479.9521484375, 1312.5040283203125)
+    dp2.LookupTable = MakeBlueToRedLT(-2479.9521,1312.5)
+    dp2.ColorAttributeType = 'POINT_DATA'
+    dp2.ColorArrayName = 'VEL'
+    Render()
+    WriteImage(filename = (impth + "glyphFilter_2.png"), view=v, Magnification=2)
+
+testdir = os.getenv("TESTDIR")
+pvdata = os.getenv("PVDATA")
+
+if __name__ == "__main__":
+ demo8(fname=pvdata+"/Data/can.ex2", impth=testdir+"/Pic/")
diff --git a/test/demo9.py b/test/demo9.py
new file mode 100755 (executable)
index 0000000..e8a60c7
--- /dev/null
@@ -0,0 +1,58 @@
+
+if not ('servermanager' in dir()):
+  from pvsimple import *
+
+import os
+
+def demo9(fname, impth):
+    """This method demonstrates the Threshold filter."""
+
+    reader = ExodusIIReader(FileName=fname)
+    v=GetActiveView()
+    Show(reader, view=v)
+    dp1 = GetDisplayProperties(reader)
+    dp1.Representation = 'Wireframe'
+    camera = GetActiveCamera()
+    camera.Elevation(-60)
+    thresholdFilter = Threshold(reader)
+    thresholdFilter.Scalars
+    ##['POINTS', 'GlobalNodeId']
+
+    thresholdFilter.Scalars = 'Temp'
+    Show(thresholdFilter)
+    thresholdFilter.ThresholdRange
+    ##[0.0, 0.0]
+    thresholdFilter.ThresholdRange = [398.55,913.15]
+    Render()
+    WriteImage(filename = (impth + "thresholdFilter_1.png"), view=v, Magnification=2)
+
+    dp2 = GetDisplayProperties(thresholdFilter)
+    thresholdFilter.PointData[:]
+    ##[Array: GlobalNodeId, Array: PedigreeNodeId, Array: Temp, Array: V, Array: Pres, Array: AsH3, Array: GaMe3, Array: CH4, Array: H2]
+
+    temp = thresholdFilter.PointData[2]
+    temp.GetRange()
+    ##(400.46258544921875, 846.694091796875)
+
+    dp2.LookupTable = MakeBlueToRedLT(400.4625,846.6909)
+    dp2.ColorAttributeType = 'POINT_DATA'
+    dp2.ColorArrayName = 'Temp'
+    Render()
+    WriteImage(filename = (impth + "thresholdFilter_2.png"), view=v, Magnification=2)
+    
+    #Set the lower threshold to 500
+    thresholdFilter.ThresholdRange[0] = 500
+    Render()
+    WriteImage(filename = (impth + "thresholdFilter_3.png"), view=v, Magnification=2)
+    
+    dp1.LookupTable = MakeBlueToRedLT(400.462, 84609)
+    dp1.ColorAttributeType = 'POINT_DATA'
+    dp1.ColorArrayName = 'Temp'
+    Render()
+    WriteImage(filename = (impth + "thresholdFilter_4.png"), view=v, Magnification=2)
+
+testdir = os.getenv("TESTDIR")
+pvdata = os.getenv("PVDATA")
+
+if __name__ == "__main__":
+ demo9(fname=pvdata+"/Data/disk_out_ref.ex2", impth=testdir+"/Pic/")
diff --git a/test/demo_14_med.py b/test/demo_14_med.py
new file mode 100755 (executable)
index 0000000..f9ff014
--- /dev/null
@@ -0,0 +1,53 @@
+""" 
+MEDReader test script. 
+Before launching the script necessary MED files has to be placed into ${TESTDIR}/MedData directory 
+"""
+
+if not ('servermanager' in dir()):
+  from pvsimple import *
+
+import sys
+import os
+import time
+
+def medread (path, impth):
+  print '============================================================'
+
+  if os.path.exists(path):
+    filelist = os.listdir(path)
+    num = len (filelist)
+    
+    for i in range(num):
+      fname = str(filelist[i])
+      if fname.rfind(".med") > -1:
+        v = GetRenderView()
+        v.UseLight = 1
+        v.CameraPosition = [0.0, 0.0, 6.7]
+        v.LightSwitch = 0
+        v.CameraClippingRange = [4.5, 9.5]
+        v.LODThreshold = 5.0
+        v.Background = [0., 0., 0.]
+        v.CameraParallelScale = 1.8
+        
+        file_med = MEDReader( FileName=(path + fname))
+        
+        time.sleep(10)
+        SetActiveSource(file_med)
+        Show()
+        ##Show (file_med, view=v)
+        ##Render(view=v)
+        Render()
+        time.sleep(10)
+        WriteImage(filename = (impth +  "medFile_" + str(i+1) + ".png"), view=v, Magnification=2)
+        print str(i+1), "Shown file is:  ", fname
+        
+        Delete(v)
+        v1 = CreateRenderView()
+        SetActiveView(v1)
+        
+
+testdir = os.getenv("TESTDIR")
+pvdata = os.getenv("PVDATA")
+
+if __name__ == "__main__":
+  medread(path=testdir+"/MedData/", impth=testdir+"/Pic/")
diff --git a/test/demo_15_med.py b/test/demo_15_med.py
new file mode 100755 (executable)
index 0000000..3dc4bac
--- /dev/null
@@ -0,0 +1,53 @@
+
+# ATTENTION. This script is prepared for the future not for current moment !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+if not ('servermanager' in dir()):
+  from pvsimple import *
+
+import os
+
+def LoadMultipleFiles_med(FilePath, FilePrefix):
+
+  TETRA_dom_fl = MEDReader( FileName = [FilePath + FilePrefix + '1' + '.med',
+                                                                               FilePath + FilePrefix + '2' + '.med', 
+                                                                               FilePath + FilePrefix + '3' + '.med',
+                                                                               FilePath + FilePrefix + '4' + '.med',
+                                                                               FilePath + FilePrefix + '5' + '.med',
+                                                                               FilePath + FilePrefix + '6' + '.med'])
+  TETRA_dom_fl.CellArrays = ['Pression', 'Temp.C', 'VitesseX']
+  TETRA_dom_fl.GlobalFamilyStatus = ['1 1 1', '1 2 1', '1 3 1', '1 4 1', '1 5 1']
+  TETRA_dom_fl.GlobalEntityStatus = ['0 203', '0 304']
+
+  rv = GetRenderView()
+  a1_Temp_C_PVLookupTable = CreateLookupTable( RGBPoints=[-1.3, 0.23, 0.3, 0.75, 200., 0.70, 0.016, 0.15],
+                                                                                            VectorMode='Magnitude',
+                                                                                            ColorSpace='Diverging',
+                                                                                            ScalarRangeInitialized=1.0 )
+
+  dr = Show()
+  dr.EdgeColor = [0.0, 0.0, 0.50]
+  dr.SelectionCellLabelColor = [0.0, 1.0, 0.0]
+  dr.SelectionPointLabelJustification = 'Center'
+  dr.SelectionCellLabelJustification = 'Center'
+  dr.ScalarOpacityFunction = []
+  dr.ColorArrayName = 'Temp.C'
+  dr.SelectionLineWidth = 2.0
+  dr.ScalarOpacityUnitDistance = 2.6738860338205099
+  dr.SelectionCellLabelFontSize = 24
+  dr.SelectionColor = [1.0, 0.0, 1.0]
+  dr.SelectionRepresentation = 'Wireframe'
+  dr.LookupTable = a1_Temp_C_PVLookupTable
+
+  rv.CameraPosition = [50.0, -29.75, 267.55447959748415]
+  rv.CameraFocalPoint = [50.0, -29.75, 0.0]
+  rv.CameraClippingRange = [248.95893480150932, 291.60779679144639]
+  rv.CenterOfRotation = [50.0, -29.75, 0.0]
+  rv.CameraParallelScale = 69.24819492232271
+
+  Render()
+
+testdir = os.getenv("TESTDIR")
+pvdata = os.getenv("PVDATA")
+
+if __name__ == "__main__":
+  LoadMultipleFiles_med(FilePath=testdir+"/TETRA_domaine_fluide/", FilePrefix="TETRA_domaine_fluide")